1.一种组件间通信方式,适用于任意组件间通信
2.使用步骤
(1)安装 pubsub: npm i pubsub-js
(2)引入:import pubsub from 'pubsub-js'
(3)接收数据:A 组件想接收数据,则在 A 组件中订阅消息,订阅的的回调留在 A 组件中
methods: {
demo() {
demo(data){...}
}
...
mounted() {
this.pubId = pubsub.subscribe('xxx', this.demo)
}
(4)提供数据:pubsub.publish('xxx', 数据)
(5)最好在 beforeDestroy 钩子中,用 pubsub.unsubscribe(this.pubId)去解绑当前组件所用到的事件
App.vue
<template>
<div class="app">
<h1>{{ msg }}</h1>
<School />
<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: '你好啊',
}
},
}
</script>
<style scoped>
.app {
background-color: gray;
padding: 5px;
}
</style>
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() {
// this.$bus.$on('hello', (data) => {
// console.log('我是school组件,收到数据了', data)
// })
this.pubId = pubsub.subscribe('hello', (notificationName, data) => {
console.log('有人发布了hello消息,hello消息的回调被执行了', data)
})
},
beforeDestroy() {
// this.$bus.$off('hello')
pubsub.unsubscribe(this.pubId)
},
}
</script>
<style lang="less" scoped>
.school {
background-color: skyblue;
padding: 5px;
}
</style>
Student.vue
<template>
<!-- 组件的结构 -->
<div class="student">
<h2>学生姓名:{{ name }}</h2>
<h2>学生性别:{{ sex }}</h2>
<button @click="sendStudentName">传递学生名称给学校</button>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name: 'Student',
data() {
return {
name: '张三',
sex: '男',
}
},
methods: {
sendStudentName() {
// this.$bus.$emit('hello', this.name)
pubsub.publish('hello', 666)
},
},
}
</script>
<style scoped>
.student {
background-color: orange;
padding: 5px;
margin-top: 30px;
}
</style>