使用全局事件总线来实现不同组件间的事件通信
创建 src/stores/event-bus.js
// bus.js
class Bus {
constructor() {
this.list = {}; // 收集订阅
}
// 订阅
$on(name, fn) {
this.list[name] = this.list[name] || [];
this.list[name].push(fn);
}
// 发布
$emit(name, data) {
if (this.list[name]) {
this.list[name].forEach((fn) => { fn(data); });
}
}
// 取消订阅
$off(name) {
if (this.list[name]) {
delete this.list[name];
}
}
}
export default new Bus;
发送
import EventBus from '@/stores/event-bus.js';
EventBus.$emit('refresh-waterfall', 'data');
接收
import EventBus from '@/stores/event-bus.js';
EventBus.$on('refresh-waterfall', () => {
// 触发操作
});