EventBus是一種發佈/訂閱事件設計模式的實踐。
在vue中適用於跨組件簡單通訊,不適應用於複雜場景多組件高頻率通訊,相似購物車等場景狀態管理建議採用vuex。javascript
添加bus.js文件
//src/service/bus.jsvue
export 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.$once(...event) }, $emit (...event) { eventHub.$emit(...event) } } }
註冊
//main.jsjava
import BUS from './service/bus' BUS(Vue)
A組件git
beforeDestroy () { //事件廣播 this.$bus.$emit('testing', color) }
B組件github
created () { //事件訂閱 this.$bus.$on('testing', (res) => { console.log(res) }) }, beforeDestroy () { this.$bus.$off('testing') }
2.普通跨組件通訊:因爲兩組件幾乎同時加載,所以建議事件廣播放在created鉤子內,事件訂閱放在mouted中便可。具體使用場景建議在兩組件分別打印生命鉤子函數進行準確判斷。vuex
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 銷燬完成狀態===============》') }