Vue封装中央事件总线插件vue-bus

1.第一步:新建vue-bus文件夹,在该文件下新建index.js

/*

封装一个中央事件总插件vue-bus,可以在任意组件间使用,而不需要导入bus

给Vue添加一个属性$bus,并代理$emit, $on, $off三个方法

*/

 1 const install = function(Vue) {
 2     const Bus = new Vue({
 3         methods: {
 4             emit (event, ...args) {
 5                 this.$emit(event, ...args);
 6             },
 7             on (event, callback) {
 8                 this.$on(event, callback);
 9             },
10             off (event, callback) {
11                 this.$off(event, callback);
12             },
13         }
14     })
15 
16     Vue.prototype.$bus = Bus;
17 }
18 
19 export default install;

2.第二步:

在main.js中使用:

import VueBus from './vue-bus';

Vue.use(VueBus);

3.第三步就可以在组件中使用了:

 1 backtoHome() {
 2         this.$bus.emit('overfl-visi',this.overflVisible);
 3         this.$router.push('/home');
 4     }
 5     
 6 
 7 created () {
 8             this.$bus.on('overfl-visi', this.changeOverflow);
 9 }
10 
11 beforeDestroy () {
12             this.$bus.off('overfl-visi', this.changeOverflow);    
13         }

使用vue-bus有两点需要注意:

第一是$bus.on应该再created钩子内使用,如果在mounted使用,它可能接收不到其他组件来自created钩子内发出的事件

第二是使用了$bus.on,在beforeDestroy钩子里应该使用$bus.off解除。因为组件销毁后,就没必要把监听的句柄储存在vue-bus里了。