Vue事件总线
一 项目结构
二 main.js
import Vue from "vue"; import App from "./App.vue"; import Toolkit from "./plugins/toolkit"; Vue.config.productionTip = false; Vue.use(Toolkit); new Vue({ render: h => h(App) }).$mount("#app");
三 toolkit.js
export default { install(Vue, options) { // 方法一:修改Vue构造函数的原型链 Vue.prototype.$eventBus = new Vue(); // 方法二:注册全局事件总线 // window.eventBus = new Vue(); } };
四 App.vue
<template> <div id="app"> <fish/> <cat/> </div> </template> <script> import Vue from "vue"; import Fish from "./components/Fish"; import Cat from "./components/Cat"; export default { name: "app", components: { Fish, Cat } }; </script> <style> </style>
五 Fish.vue
<template> <div> <h3>鱼🐟</h3> <button @click="swim">按钮</button> </div> </template> <script> export default { methods: { swim() { console.log("鱼在水里游"); this.$eventBus.$emit("swim",'龙利鱼'); } } }; </script> <style> </style>
六 Cat.vue
<template> <h3>猫🐱</h3> </template> <script> export default { created() { this.$eventBus.$on("swim", function(fishName) { console.log("捕鱼", fishName); }); }, // 组件销毁时,要取消监听。否则,回调函数仍然会执行。 beforeDestroy() { console.log("取消监听"); this.$eventBus.$off("swim"); } }; </script> <style> </style>
七 运行效果