美文网首页
vue组件通信原理之$bus

vue组件通信原理之$bus

作者: 荔桑 | 来源:发表于2020-09-29 23:52 被阅读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')

相关文章

网友评论

      本文标题:vue组件通信原理之$bus

      本文链接:https://www.haomeiwen.com/subject/aveyuktx.html