vue里面的eventBus使用
// eventBus.jsexport default new Vue();// on.jsimport eventBus from './eventBus.js'eventBus.$on(test, function(val) { console.log(val); // string})// emit.jsimport eventBus from './eventBus.js'eventBus.$emit(test, 'string');
本质是发布订阅模式
class EventBus { constructor() { this.callback = {}; } $on(name, fn) { // 订阅 this.callback[name] = this.callback[name] || []; // 需要在多个地方订阅,所以需要使用数据 this.callback[name].push(fn); } $emit(name, ...args) { // 发布 if (this.callback[name]) { this.callback[name].forEach(fn => { fn(...args) }) } } }
发布订阅步骤
- 首先创建一个类,里面有一个callback对象
- 创建订阅方法,参数为订阅名称和具体执行的函数
- 然后把订阅名称作为callback对象的对象名