事件总线

157 阅读1分钟

全局事件总线(Global Eevent Bus):适用于任意组件间通信: test绑定自定义事件。 触发事件。 1、保证所有组件都能看到。 2、能帮到on,on,off,$emit。

1、windows。VueComponent原型对象上。都不推荐。 VueComponent.prototype._proto=== Vue.proptoye 放在Vue.prototype.x = {}//vm,vc

2、this. 可以调用on。是因为thisvue的实例对象。Vue的原型对象(prototype)上有on。是因为this是vue的实例对象。 Vue的原型对象(prototype)上有on,off,off,emit。

const Demo = Vue.extend() const x = new Demo()

beforeCreate() { Vue.prototyoe.$bus(总线) = this }。this就是new Vue()。

this.x.$on.

1、安装全局事件总线: new Vue({ beforeCreate({Vue.prototype.bus=this//安装全局事件总线,bus =this//安装全局事件总线,bus就是当应用的vm})} ) 2、使用事件总线: 1、接受数据: A组件想要接受数据,则A组件中bus绑定自定义事件,事件的回调在A组件自身。 methods(){ demo(data){...} } mounted(){ this.bus.$on('xxxx',数据) }

  2、提供数据: this.$bus.$emit('XXX',数据)
  

3、最好在beforeDestory钩子中,用$off解绑用到的事件。

整个通信就是干两件事:1是数据,2个函数。。

收的一放,绑定回调this.bus.bus.on(+函数名+函数)。

发的一方,this.bus.bus.emit(+函数名,+函数值)