vue组件通信之$bus(事件总线)

$bus 思路是在全局挂载一个实例,通过这个实例里的事件派发和事件监听实现跨组件通信,设计模式叫做观察者模式。

使用场景:跨多层级组件传参,不顺路要坐bus。

第一步

创建一个$bus对象 (main.js)

class Bus {
  constructor){
    this.callbacks = {}
  }
  $onname, fn){
    this.callbacks[name] = this.callbacks[name] || []
    this.callbacks[name].pushfn)
  }
  $emitname, args){
    ifthis.callbacks[name]){
      this.callbacks[name].forEachcb => cbargs))
    }
  }
}

第二步 

实例化Bus并挂载到vue全局上 (main.js)

Vue.prototype.$bus = new Bus);

经过上面两个步骤我们就创建了一个全局的$bus对象,并且可以随时随地调用它里面的$on和$emit方法。

第三步

在需要讲数据传递出去的组件里做事件派发,即调用$emit方法

第一个参数是事件名称,第二个参数是要传递的数据

this.$bus.$emit"event1","somethings from helloworld");

第四步

在需要接收数据的组件里做事件监听,即调用$on方法,监听的方法一般写在mounted里面

this.$bus.$on"event1",functionaaa){
     console.logaaa)
})

以上就是事件总线的方法

Published by

风君子

独自遨游何稽首 揭天掀地慰生平