手动实现简单的Bus总线

在emit里面遍历数组 取出函数 执行函数

main.js
import Bus from './utils/bus';
Vue.prototype.$bus = new Bus();
bus.js
export default class Bus {
  constructor() {
    // {
    //   eventName1:[fn1,fn2],
    //   eventName2:[fn3,fn4],
    // }
    this.callbacks = {};
  }
  $on(name, fn) {
    this.callbacks[name] = this.callbacks[name] || [];
    this.callbacks[name].push(fn);
  }
  $emit(name, args) {
    if (this.callbacks[name]) {
      // 存在 遍历所有callback
      this.callbacks[name].forEach(cb => cb(args));
    }
  }
}
使用
//派发
this.$bus.$emit('event-bus','测试eventBus')
//接收
this.$bus.$on("event-bus", msg => {
      this.msg = "接收event-bus消息:" + msg;
    });

你可能感兴趣的:(手动实现简单的Bus总线)