Vue 消息的订阅与发布(pubsub)
这是一种组件间的通信方式,适用于:任意组件间通信
安装 pubub
npm i pubsub-js
引入 pubub
import pubsub from 'pubsub-js'
提供数据
pubsub.publish('xxx',数据)
接收数据
A 组件需要接收数据,则在 A 组件中订阅消息,订阅的回调留在 A 组件自身
methods: {
demo(msgName, data){...}
},
mounted() {
this.pid = pubsub.subscribe('xxx',this.demo)
}
接收数据还有一种写法
mounted() {
this.pid = pubsub.subscribe('xxx',(msgName, data)=>{...})
}
注意:最好在 beforeDestroy 钩子中,去取消订阅
beforeDestroy() {
pubsub.unsubscribe(this.pid)
}
实例
src 文件结构'
|-- src
|-- App.vue
|-- main.js
|-- components
|-- MySchool.vue
|-- MyStudent.vue
App.vue
<template>
<div>
<my-school/>
<my-student/>
</div>
</template>
<script>
import MySchool from "@/components/MySchool";
import MyStudent from "@/components/MyStudent";
export default {
name: 'App',
components: {
MySchool,
MyStudent
}
}
</script>
<style>
</style>
main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
MySchool.vue
<template>
<div class="demo">
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
</template>
<script>
// 引入 pubub
import pubsub from 'pubsub-js'
export default {
name: "MySchool",
data() {
return {
name: 'ABC',
address: '长沙'
}
},
methods: {
demo(msgName, data) {
console.log('有人发布了 hello 消息,hello 消息的回调执行了', msgName, data)
}
},
// 接收数据
mounted() {
this.pubId = pubsub.subscribe('hello', this.demo)
},
beforeDestroy() {
pubsub.unsubscribe(this.pubId)
}
}
</script>
<style scoped>
.demo {
background-color: #9ebbfc;
}
</style>
MyStudent.vue
<template>
<div class="demo">
<h2>学生姓名:{{name}}</h2>
<h2>学生年龄:{{age}}</h2>
<button @click="sendStudentName">把学生姓名给 School 组件</button>
</div>
</template>
<script>
// 引入 pubub
import pubsub from 'pubsub-js'
export default {
name: "MyStudent",
data() {
return {
name: '张三',
age: 19
}
},
methods: {
// 提供数据
sendStudentName() {
pubsub.publish('hello', this.name)
}
}
}
</script>
<style scoped>
.demo {
background-color: #b2dece;
}
</style>

浙公网安备 33010602011771号