1.全局事件总线,顾名思义,可以适用于任意组件间通信,我们需要通过$bus这个中间傀儡来实现,我们可以把$bus安装到Vue身上,这样可以让所有组件都能看到它,
1.1安装全局事件总线:我们可以在new Vue()时,在其beforeCreate生命周期里,加上Vue.prototype.$bus=this,此时的this指向的是Vue,由于Vue只有一个,并且都在各组件的原型链上
创建vm
new Vue({
el:'#app',
render: h =>h(App),
beforeCreate() {
Vue.prototype.$bus = this
}
})
1.2.接收数据:我们可以给需要接收数据的一方加上
mounted(){
this.$bus.$on('指令名',(data)=>{
console.log('收到了数据',data)
})
},
beforeDestory(){
this.$bus.off('指令名')
}
1.3.提供数据:我们可以给需要提供数据的一方加上
methods:{
sendStudentName(){
this.$bus.$emit('指令名',数据)
}
}
提供数据的一方
2.消息订阅与发布
2.1安装js库
npm i pubsub-js
2.2确定收发方
发送方:
methods:{
sendStudentName(){
pubsub.publish('hello',666)
}
}
接收方:
写法一:
mounted(){ //其中需要注意的是此时函数里的this已经不指向VueComponent,
//我们可以写成箭头函数的形式
this.pubId = pubsub.subscribe('hello',function(msgName,data){
console.log('有人发布了hello消息',hello消息的回调执行了,msgName,data)
}
},
beforeDestory(){
pubsub.unsubscribe(this.pubId)
}
写法二:
methods: {
demo(magName,data){
console.log('hello消息收到了',data)
}
},
mounted(){
this.pubId = pubsub.subscribe('hello',this.demo)
},
beforeDestory(){
pubsub.unsubscribe(this.pubId)
}