EventBus
EventBus是一種發布/訂閱事件設計模式的實踐。
在vue中適用于跨組件簡單通信,不適應用于復雜場景多組件高頻率通信,類似購物車等場景狀態管理建議采用vuex。
掛載EventBus到vue.prototype
添加bus.js文件
//src/service/bus.jsexport default (Vue) => { const eventHub = new Vue() Vue.prototype.$bus = { /** * @param {any} event 第一個參數是事件對象,第二個參數是接收到消息信息,可以是任意類型 * @method $on 事件訂閱, 監聽當前實例上的自定義事件。https://cn.vuejs.org/v2/api/#vm-on * @method $off 取消事件訂閱,移除自定義事件監聽器。 https://cn.vuejs.org/v2/api/#vm-off https://github.com/vuejs/vue/issues/3399 * @method $emit 事件廣播, 觸發當前實例上的事件。 https://cn.vuejs.org/v2/api/#vm-emit * @method $once 事件訂閱, 監聽一個自定義事件,但是只觸發一次,在第一次觸發之后移除監聽器。 https://cn.vuejs.org/v2/api/#vm-once */ $on (...event) { eventHub.$on(...event) }, $off (...event) { eventHub.$off(...event) }, $once (...event) { eventHub.$emit(...event) }, $emit (...event) { eventHub.$emit(...event) } }}注冊//main.jsimport BUS from './service/bus'BUS(Vue)
注意事項
使用場景
1.跨路由組件使用eventbus通信
假設a路由跳轉b路由需要通過eventbus通信,先觀察路由跳轉前后a,b組件的生命周期鉤子函數,可以發現兩者是交叉執行的。
由于事件訂閱必須在事件廣播前注冊,所以事件訂閱可以放在b組件beforeCreate,created,beforeMout鉤子函數中,而事件廣播可以放在a組件的beforeDestroy,destroyed中。
取消事件訂閱必須跟事件訂閱成對出現,否則會重復訂閱,對javascript性能造成不必要的浪費。因此B組件銷毀前需取消當前事件訂閱。
A組件
beforeDestroy () { //事件廣播 this.$bus.$emit('testing', color) }
B組件
created () { //事件訂閱 this.$bus.$on('testing', (res) => { console.log(res) }) }, beforeDestroy () { this.$bus.$off('testing') }
2.普通跨組件通信:由于兩組件幾乎同時加載,因此建議事件廣播放在created鉤子內,事件訂閱放在mouted中即可。具體使用場景建議在兩組件分別打印生命鉤子函數進行準確判斷。
beforeCreate: function () { console.group('A組件 beforeCreate 創建前狀態===============》') }, created: function () { console.group('A組件 created 創建完畢狀態===============》') }, beforeMount: function () { console.group('x組件 beforeMount 掛載前狀態===============》') }, mounted: function () { console.group('x組件 mounted 掛載結束狀態===============》') }, beforeUpdate: function () { console.group('x組件 beforeUpdate 更新前狀態===============》') }, updated: function () { console.group('x組件 updated 更新完成狀態===============》') }, beforeDestroy: function () { console.group('x組件 beforeDestroy 銷毀前狀態===============》') }, destroyed: function () { console.group('x組件 destroyed 銷毀完成狀態===============》') }
總結
以上所述是小編給大家介紹的vue采用EventBus實現跨組件通信及注意事項小結,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答