事件總線
事件總線主要是實(shí)現(xiàn)一些任意的或非父子關(guān)系的組件之間的數(shù)據(jù)通信
實(shí)現(xiàn)一個(gè)事件總線功能需要:
- 事件派發(fā)
$emit - 監(jiān)聽
$on - 回調(diào)管理
// Bus:事件派發(fā)、監(jiān)聽和回調(diào)管理
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))
}
}
}
// main.js
Vue.prototype.$bus = new Bus()
// child1:監(jiān)聽child2中的事件及傳值
this.$bus.$on('event-from-child2', msg => {
console.log('Child1:', msg);
});
// child2:派發(fā)事件
this.$bus.$emit('event-from-child2', 'some msg from child2')
實(shí)踐中通常?Vue代替Bus,因?yàn)閂ue已經(jīng)實(shí)現(xiàn)了相應(yīng)接?