vue组件通信原理之$bus

2020-09-29  本文已影响0人  荔桑

事件总线$bus主要使用vue高级API vm.$on 原理,例:

// main.js
Vue.prototype.$bus = new Vue(); // $bus是原型对象上的实例
// child1
this.$bus.$on('foo', handle)  //子组件通过$bus监听事件
// child2
this.$bus.$emit('foo')  //子组件通过$emit触发事件

以上写法等同于以下写法:

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()
// child1
this.$bus.$on('foo', handle)
// child2
this.$bus.$emit('foo')
上一篇 下一篇

猜你喜欢

热点阅读