一、全局事件总线
1.一种组件间通信的方式,适用于任意组件间通信
2.安装全局事件总线:
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
/* 1.第一种写法 */
// const Demo = Vue.extend({})
// const d = new Demo()
// Vue.prototype.x = d // 把Demo实例挂载到Vue的原型上,这样所有Vue实例都可以访问到x
new Vue({
el: '#app',
render: h => h(App),
/* 2. 第二种写法 */
beforeCreate() {
Vue.prototype.$bus = this // 安装全局总线
},
})
3、使用事件总线
发送数据:
this.$bus.$emit('事件名',数据)
接收数据:
methods:{
receive(data){....}
},
......
mounted(){
this.$bus.$on('xxxx',this.demo) //xxxx为B组件中触发的事件名
//或this.$bus.$on('xxxx',(data)=>{....}) //data为传递过来的数据 注意为箭头函数形式,this的指向才是vm,若是正常函数形式,this指向为undefined
}
解绑事件
最好在beforeDestory钩子中,用$off去解绑当前组件所用到的事件。
二、消息订阅与发布 (适用于任意组件间通信)
1、它需要安装 pubsub,我们打开 VScode 的控制台,输入 npm i pubsub-js,进行安装
在传数据和接收数据的组件中都要通过 import pubsub from ‘pubsub-js’ 引入这个文件
接收数据:
this.pubId = pubsub.subscribe('hello',(msgName,data)=>{
console.log('我接收到数据了',data);
})
发送数据:
methods: {
sentMyName(){
pubsub.publish('hello',this.myName)
}
},
删除订阅消息:
beforeDestroy() {
pubsub.unsubscribe(this.pubId)
},