今天继续肝Vue的基础知识,来学习一下消息的发布与订阅,go!!!
定义:
一种组件间通信的方式,适用于任意组件间通信
使用步骤
安装pubsub:npm - pubsub-js
引入:import pubsub from 'pubsub-js'
接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件资深
mounted() {
// this.$bus.$on('hello', (data) => {
// console.log('我是School,收到了数据:', data)
// })
this.pubId = pubsub.subscribe('hello', function (msgName, data) {
console.log('有人发布hello消息,hello消息的回调被执行了', msgName, data)//订阅消息
})
},
提供数据:pubsub.publish('xxx',数据)
最好在beforeDestory钩子中,用pubsub.ubsubscribe(pid)去取消订阅
### School.vue
<template>
<div class="school">
<h1>学校名称:{{name}}</h1>
<h1>学校地址:{{address}}</h1>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name: 'SchoolVue',
data() {
return {
name: '西航',
address: '西安',
}
},
mounted() {
// this.$bus.$on('hello', (data) => {
// console.log('我是School,收到了数据:', data)
// })
this.pubId = pubsub.subscribe('hello', function (msgName, data) {
console.log('有人发布hello消息,hello消息的回调被执行了', msgName, data)
})
},
beforeDestroy() {
// this.$bus.$off('hello')
pubsub.unsubscribe(this.pubId)
},
}
</script>
<style>
.school {
background-color: blue;
padding: 5px;
margin-top: 30px;
}
</style>
### Student.vue
<template>
<div class="student">
<h1>学生姓名:{{ name }}</h1>
<h1>年龄:{{ age }}</h1>
<button @click="sendStudentName">点我发送数据</button>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name: 'StudentVue',
data() {
return {
name: '空谷有来人',
age: 19,
}
},
methods: {
sendStudentName() {
// this.$bus.$emit('hello', this.name)
pubsub.publish('hello', 666)
},
},
}
</script>
<style>
.student {
background-color: green;
padding: 5px;
margin-top: 30px;
}
</style>
我是空谷有来人,谢谢支持!