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
的插件,那么就可以在組件之間使用我衬,而不需要導入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ù)進來,使用...args
可以把當前參數(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
,不需要每一個組件都導入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);
}