Vue中的全局事件总线和消息的订阅与发布都是可以实现组件间的相互通信。
一、全局事件总线
Vue中的全局事件总线可以任意组件间的相互通信,其原理就是创建一个东西能够让所有的组件和vm都能识别到,这个东西就可以叫做全局事件总线。
首先需要安装全局事件总线,也就是在main.js中添加beforeCreated生命周期钩子,因为此时模板还未解析,所以选择这个时候安装总线,具体代码是:
new Vue({
el:'#app',
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus=this
},
}).$mount('#app')
发送方发送数据:
通过在methods中编写一个方法,然后通过:this.$bus.$emit传递数据;
接收方接收数据:
在mounted中通过:this.$bus.$on接收数据。
例子:
发送方Student组件:
<template>
<!-- 组件的结构 -->
<div class="student">
<h2>{{name}}</h2>
<h2>{{age}}</h2>
<button @click="sendStudentName">把学生名给school</button>
</div>
</template>
<script>
export default{
name:'StudentName',
data(){//data一定要写成函数的形式
return {
name:'tom',
age:18,
}
},
methods:{
sendStudentName(){
this.$bus.$emit('hello',this.name)
}
}
}
</script>
<style>
.student{
background-color: greenyellow;
}
</style>
接收方School组件:
<template>
<!-- 组件的结构 -->
<div class="demo">
<h2>{{schoolName}}</h2>
<h2>{{address}}</h2>
</div>
</template>
<script>
export default {
name:'SchoolName',
data(){//data一定要写成函数的形式
return {
schoolName:'河南',
address:'洛阳',
}
},
mounted(){
console.log('school',this);
this.$bus.$on('hello',(data)=>{
console.log('school组件,收到了数据',data);
})
},
beforeDestroy(){
this.$bus.$off('hello')
}
}
</script>
二、消息的订阅与发布
实现消息的订阅与发布,首先需要安装一个库,可以选择安装pubsub-js库;
第一步:引入pubsub-js库:import pubsub from 'pubsub-js'
第二步:订阅方订阅消息:
mounted(){
this.pubId=pubsub.subscribe('hello',function(msgName,data){
console.log('发布了hello消息',msgName,data);
})
},
第三步:发布方发布消息:
methods:{
sendStudentName(){
pubsub.publish('hello',this.name)
}
}
如果需要取消订阅:
beforeDestroy(){
// this.$bus.$off('hello')
pubsub.unsubscribe(this.pubId)
}