Vue - 消息订阅与发布
一种组件间通信方式,适用于任意组件间通信。
使用步骤
1.安装pubsub: npm i pubsub-js
2.引入:import pubsub from 'pubsub-js'
3.接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。pubsub.subscribe('xxx',回调函数)
<template>
<div>
<h2>{{receiveName}}</h2>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name: "School",
data(){
return{
receiveName:""
}
},
mounted() {
this.pid = pubsub.subscribe("receiver",(msgName,data) =>{
console.log(msgName+"订阅成功!");
this.receiveName = data;
})
}
}
</script>
4.提供数据:pubsub.publish('xxx',数据)
<template>
<div>
<button @click="send">发送订阅</button>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name: "Student",
data(){
return{
name:"张三"
}
},
methods:{
send(){
pubsub.publish('receiver',this.name);
}
}
}
</script>
5.最好在beforeDestory钩子中,用pubsub.unsubscribe(pid)
取消订阅。