消息的订阅与发布(基本不用)
消息订阅与发布(pubsub)消息订阅与发布是一种组件间的通信的方式,适用于任意组件间通信
消息订阅与发布
1.订阅消息∶消息名
2.发布消息︰消息内容
消息订阅与发布的工作流程:
(A是订阅者,B是发布者)
使用步骤
- 安装pubsub: npm i pubsub-js
- 引入: import pubsub from ‘pubsub-js’
- 接收数据:A组件想接收数据,则在A组件种订阅消息,订阅的回调留在A组件自身
export default{
methods:{
demo(msgName,data){...}
}
...
mounted(){
this.pid=pubsub.subscribe('xxx',this.demo)
}
}
- 提供数据:pubsub.publish(‘xxx’,data)
- 最好在beboreDestroy 钩子中,使用pubsub.unsubscribe(pid) 取消订阅
src/components/School.vue
<template>
<div class="school">
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name:'School',
data() {
return {
name:'尚硅谷',
address:'北京',
}
},
mounted() {
// console.log('School',this)
/* this.$bus.$on('hello',(data)=>{
console.log('我是School组件,收到了数据',data)
}) */
this.pubId = pubsub.subscribe('hello',(msgName,data)=>{
console.log(this)
console.log('有人发布了hello消息,hello消息的回调执行了',msgName,data)
})
},
beforeDestroy() {
// this.$bus.$off('hello')
pubsub.unsubscribe(this.pubId)
},
}
</script>
<style scoped>
.school{
background-color: skyblue;
padding: 5px;
}
</style>
src/components/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:'男',
}
},
mounted() {
// console.log('Student',this.x)
},
methods: {
sendStudentName(){
// this.$bus.$emit('hello',this.name)
pubsub.publish('hello',666)
}
},
}
</script>
<style lang="less" scoped>
.student{
background-color: pink;
padding: 5px;
margin-top: 30px;
}
</style>