Vue-全局事件总线/消息订阅与发布
前面很详细的介绍了子组件与父组件通信 以及 父组件如何与子组件通信
下面将给大家介绍两种组件间通信的方式,适用于任意组件间通信
全局事件总线
? 安装全局事件总线
new Vue({ .... beforeCreate(){ //安装全局事件总线 Vue.prototype.$bus = this }, .... })
? 使用事件总线
1、接受数据:A组件想接受数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身
//方法一: methods() { demo(data){....} .... mouted(){ this.$bus.$on('xxx',this.demo) } beforeDestroy() { //在摧毁School组件之前先讲傀儡bus解绑 this.$bus.$off("hello"); }, //方法二: this.$bus.$on('xxx',箭头函数)
2、提供数据B组件 this.$bus.$emit('xxx',数据)
最好在beforeDestroy钩子中,用$off去解绑当前组件最用到的事件
消息订阅与发布
安装 pubsub
npm i pubsub-js
引入 [需要在每个组件中引入]
import pubsub from 'pubsub-js'
接受数据 A组件想接受数据,则在A组件中订阅消息,订阅的回调函数在A组件自身
//方法一:
methods() {
demo(data){.....}
}
mouted() {
this.pubId = pubsub.subscribe('xxx',this.demo) //订阅消息
}
//方法二:
mouted() {
this.pubId = pubsub.subscribe('xxx',(msgName,data)=>{...} ) //订阅消息
}
提供数据
pubsub.publish('xxx',数据)
最好在beforeDestroy钩子中,用PubSub.unsubscribe(subId)去取消订阅