Vue全局事件总线、消息与订阅发布
一、全局事件总线
1. 一种组件间通信的方式,适用于任意组件间通信。
2. 安装全局事件总线:
new Vue({......beforeCreate() {Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm},......})
3. 使用事件总线:
(1). 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件回调留在A组件自身。
//使用箭头函数mounted() {this.$bus.$on("eventName", data => {console.log("我是A组件,收到了数据:", data)});}//或者标准写法methods(){callbackName(data){console.log("我是A组件,收到了数据:", data)}},mounted(){this.$bus.$on('eventName',this.callbackName)}
(2). 提供数据:
this.$bus.$emit("eventName", data)
4. 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。
beforeDestroy() {this.$bus.$off("eventName")}
二、消息与订阅发布
1. 一种组件间通信的方式,适用于任意组件间通信。
2. 使用步骤:
(1). 安装pubsub:```yarn add pubsub-js```
(2). 引入: ```import pubsub from 'pubsub-js'```
3. 接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。
//箭头函数mounted(){this.pubId = pubsub.subscribe("hello", (_, data) => {console.log("有人发布了hello消息,hello消息的回调执行了", data)})}//或标准写法methods(){callbackName(msgName, data){console.log("有人发布了hello消息,hello消息的回调执行了", data)}},mounted(){this.pubId = pubsub.subscribe("hello", this.callbackName)}
4. 提供数据:
pubsub.publish("hello", data)
5. 最好在beforeDestroy钩子中,用```PubSub.unsubscribe(pid)```去取消订阅。
beforeDestroy() {pubsub.unsubscribe(this.pubId)}
