我記得我寫過這個邏輯,就是在vue 的原型上加個全局的分發器,然後大家都可以很開心的使用
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
class Bus {
constructor() {
this.callbacks = {}
}
on(name, fn) {
this.callbacks[name] = this.callbacks[name] || [];
this.callbacks[name].push(fn);
}
emit(name, args) {
if (this.callbacks[name]) {
this.callbacks[name].forEach(cb => {
cb(args)
})
}
}
}
Vue.prototype.$bus = new Bus();
new Vue({
render: h => h(App)
}).$mount('#app')
具體使用就簡單了

一個發送事件,一個接受事件,這樣就可以實作在任何 元件間進行資料傳遞,
說白了就java 中的 觀察者模式
我們繼續複習下插槽的知識