全局事件总线
-
一种组件间通信的方式,适用于任意组件间通信。
-
安装全局事件总线:
new Vue({ ...... beeforeCreate(){ Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm }, ...... })
-
使用事件总线:
-
接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身.
methods(){ demo(data){......} }, mounted(){ this.$bus.$on('hello',this.demo);//xxxx为事件名(自定义) }
-
B组件提供传递数据:
this.$bus.$emit('xxxx',数据)
sendData(){ this.$bus.$emit('hello',数据) }
-
-
最好在beforeDestroy钩子中,用 o f f 去 解 绑 当 前 组 件 所 用 到 的 事 件 : ‘ t h i s . off去解绑当前组件所用到的事件:`this. off去解绑当前组件所用到的事件:‘this.bus.$off(‘xxxx’)`
beforeDestroy(){ this.$bus.$off('hello') }