Case 1:
1、新建event.js文件,初始化
// event-bus.js
importVuefrom 'vue'
exportconstEventBus = newVue()
2、在發(fā)送以及接收的組件中都引入此 event.js
import {
EventBus
}from "../event-bus.js";
3、發(fā)送組件加入代碼
EventBus.$emit("hello", this.number);
4、接收組件加入代碼
EventBus.$on("hello", (number) = > {
console.log(number)
});
Case 2:
直接在項目中的main.js初始化EventBus,具體發(fā)送、接收,同上Case1
// main.js
Vue.prototype.$EventBus = new Vue()
Case3:
解釋說明:中央事件總線bus,其作為一個簡單的組件傳遞事件,用于解決跨級和兄弟組件通信的問題,將其封裝為一個Vue的插件,那么就可以在組件之間使用,而不需要導(dǎo)入bus
1、新建目錄vue-bus,在目錄里新建vue-bus.js文件,具體代碼如下:
//vue-bus.js
const install = function(Vue) {
const Bus = new Vue({
methods: {
emit(event, ...args) {
this.$emit(event, ...args);
},
on(event, callback) {
this.$on(event, callback);
},
off(event, callback) {
this.$off(event, callback);
}
}
});
Vue.prototype.$bus = Bus;
};
export default install;
注:emit(event,...args)中的...args是函數(shù)參數(shù)的解構(gòu),因為不知道組件會傳遞多少個參數(shù)進(jìn)來,使用...args可以把當(dāng)前參數(shù)到最后的參數(shù)全部獲取到。
2、在main.js中使用插件:
//main.js
import VueBus from './vue-bus/vue-bus';
Vue.use(VueBus);
3、發(fā)送組件加入代碼
this.$bus.emit('hello',this.number,this.number2);
4、接收組件加入代碼
this.$bus.on('hello', (number, number2) = > {
console.log(number)
console.log(number2)
})
綜上所述,對于Case3的方式,通過插件的形式使用后,所有的組件都可以直接使用$bus,不需要每一個組件都導(dǎo)入bus組件。
有兩點需要注意:
1、$bus.on應(yīng)該在created鉤子內(nèi)使用,如果在mounted使用,有可能接收不到其他組件來自created鉤子內(nèi)發(fā)出的事件。
2、使用了$bus.on,在beforeDestroy鉤子里應(yīng)該再使用$bus.off解除,因為組件銷毀后,沒有必要把監(jiān)聽句柄存儲在vue-bus里了。
beforeDestroy() {
this.$bus.off('hello', something);
}