1. 在这里我们使用pubsub.js包
npm i pubsub-js
2. 在要进行消息发布与订阅的组件中导入包
import pubsub from 'pubsub-js'
3. 消息发布方 Student.vue
<template>
<div class="student">
<h2 >学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<button @click="sendStudentName">把学生的名字给School</button>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name:'Student',
data() {
return {
name:'张三',
sex:'男',
}
},
methods:{
sendStudentName(){
pubsub.publish('hello',this.name)
}
}
}
</script>
<style scoped>
.student{
background-color: blue;
padding: 5px;
}
</style>
4. 消息订阅方 School.vue
<template>
<div class="school">
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name:'School',
props:['getSchoolName'],
data() {
return {
name:'你好',
address:'北京',
}
},
mounted(){
// msg 是消息名,data是消息内容 每条消息拥有自己独有的ID 用箭头函数传值避免this指向错误
this.pubId = pubsub.subscribe('hello',(msg,data)=>{
console.log('hello消息订阅成功',msg,data)
})
},
// 根据独有ID取消订阅,释放资源
beforeDestroy(){
pubsub.unsubscribe(this.pubId)
}
}
</script>
<style scoped>
.school{
background-color: orange;
padding: 5px;
}
</style>