src_消息订阅与发布
# 代码
# 代码路径
$ tree -N
.
├── App.vue
├── components
│ ├── School.vue
│ └── Student.vue
└── main.js
1
2
3
4
5
6
7
2
3
4
5
6
7
# App.vue
<template>
<div class="app">
<h1>{{msg}} {{studentName}}</h1>
<School></School>
<Student></Student>
</div>
</template>
<script>
import School from './components/School.vue'
import Student from './components/Student.vue'
export default {
name:'App',
components:{School,Student},
data() {
return {
msg:'你好啊!',
studentName:'',
}
}
}
</script>
<style>
.app{
background-color: gray;
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 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:'shangguigua',
address:'beijing'
}
},
methods: {
demo(msgName,data){
console.log('有人发布了hello消息,hello消息的回调执行了',data);
}
},
mounted() {
// this.$bus.$on('hello',(data)=>{
// console.log('我是School组件,收到了数据',data);
// })
this.pubId = pubsub.subscribe('hello',this.demo)
},
beforeDestroy() {
// this.$bus.$off('hello')
// 取消订阅
pubsub.unsubscribe(this.pubId)
},
}
</script>
<style scoped>
.school{
background-color: blue;
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 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:'eryajf',
sex:'男',
number:1
}
},
methods: {
sendStudentName(){
// this.$bus.$emit('hello',this.name)
pubsub.publish('hello',this.name)
}
},
}
</script>
<style scoped>
.student{
background-color: orange;
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# main.js
import Vue from "vue"
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
el: '#app',
components:{App},
render: h => h(App),
});
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 笔记
- 一种组件间通信的方式,适用于任意组件间通信。
- 使用步骤:
- 安装 pubsub:
npm i pubsub-js
- 引入:
import pubsub from 'pubsub-js'
- 接收数据:A 组件想接收数据,则在 A 组件中订阅消息,订阅的回调留在 A 组件自身。
```js
methods(){
demo(data){......}
}
......
mounted() {
this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息
}
```
- 提供数据:
pubsub.publish('xxx',数据)
- 最好在
beforeDestroy
钩子中,用PubSub.unsubscribe(pid)
去取消订阅
上次更新: 2024/02/28, 13:00:35