// 创建一个中央事件总线
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.emit('foo')
this.on('foo', this.handle)