vue Bus

31 阅读1分钟
// 创建一个中央事件总线
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() //将中央事件总线挂载在原型上

另一种方式

Vue.prototype.$bus = new Vue() //vue已经实现了Bus的功能

this.bus.bus.emit('foo')

this.bus.bus.on('foo', this.handle)