這個集中式的事件中間件就是 Bus。我習慣將bus定義到全局:
app.js
var eventBus = {
install(Vue,options) { Vue.prototype.$bus = vue } }; Vue.use(eventBus);
然后在組件中,可以使用$emit, $on, $off 分別來分發、監聽、取消監聽事件:
分發事件的組件
// ... methods: { todo: function () { this.$bus.$emit('todoSth', params); //params是傳遞的參數 //... } }
監聽的組件
// ... created() { this.$bus.$on('todoSth', (params) => { //獲取傳遞的參數並進行操作 //todo something }) }, // 最好在組件銷毀前 // 清除事件監聽 beforeDestroy () { this.$bus.$off('todoSth'); },
如果需要監聽多個組件,只需要更改 bus 的 eventName:
// ... created() { this.$bus.$on('firstTodo', this.firstTodo); this.$bus.$on('secondTodo', this.secondTodo); }, // 清除事件監聽 beforeDestroy () { this.$bus.$off('firstTodo', this.firstTodo); this.$bus.$off('secondTodo', this.secondTodo); },