消息订阅和发布(pubsub)
1.一种组件间通信的方式 适用于任意组件间通信
2.使用步骤:
(1)安装pubsub:命令npm i pubsub-js
(2)引入:import pubsub from ‘pubsub-js’
3.在App组件中引入对应的自定义组件
<template>
<div class="app">
<h1>{{msg}}</h1>
<School/>
<Student/>
</div>
</template>
<script>
// 引入组件 汇总所有需要的组件 这个是模块化的引入
import School from "./components/School";
import Student from './components/Student.vue';
export default {
name: "App",
data() {
return {
msg:'根组件名称',
studentName:''
};
},
// 注册组件
components: {
School,
Student,
},
};
</script>
<style >
.app{
background-color: gray;
}
</style>
在子组件Student中
<template>
<div class="student">
<h2>学生姓名:{{ name }}</h2>
<h2>学生性别:{{ sex }}</h2>
<button @click="sendStudentName">把Student组件的name传给School组件</button>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name: "Student",
data() {
return {
name:"共产主义接班人",
sex:24,
};
},
methods:{
sendStudentName(){
// //触发对应的自定义事件
// this.$bus.$emit('hello',this.name)//绑定的事件名 不可重复
//发布消息
pubsub.publish('hello',888)
}
}
};
</script>
<style scoped>
.student{
background-color: rgb(131, 167, 228);
padding: 5px;
}
</style>
(3)接收数据:A组件想接收数据 则在A组件中订阅消息 订阅的回调留在A组件自身.先订阅(确定消息名称)
methods(){
demo(data){…}
}
…
mounted(){
this.pid = pubsub.subscribe(‘xxx’,this.demo)//订阅消息
}
4.提供数据:pubsub.publish(‘xxx’,数据)
5.最好在beforeDestroy钩子中 用PubSub.unsubscribe(pid) 取消订阅
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/163344.html