当前位置:网站首页>消息订阅与发布
消息订阅与发布
2022-07-03 13:27:00 【十八岁讨厌编程】
原理
消息的订阅与发布同样可以实现任意两个组件间的通信
其分为两个步骤:
- 订阅消息
- 发布消息
接下来我们通过一个例子去理解它的步骤:
现在我们想要实现组件A与C之间的通信(假设是组件C发送数据给A组件):
- 首先组件A要订阅一个消息(我们假设这个消息名叫demo)
- 随后我们再制定一个回调(我们假设这个回调的名字是test)
- 组件C发送消息,并携带着数据(我们也要将这个消息命名为demo)
- C组件一旦发布了消息,因为A组件订阅了这个消息,所以相应的回调函数会被执行,数据以参数的形式传递给了A组件。
所以说这个消息名很重要,你订阅的时候是什么名,你发布的时候就是什么名。
原生js无法轻松的实现消息的订阅与发布。所以我们一般是借助第三方库去完成这个功能。
这里我使用的是pubsub.js,它可以在任意框架中实现消息的订阅与发布。
语法注解
首先我们安装pubsub.js:
npm i pubsub-js
引入语法:
import pubsub from 'pubsub.js'
这个引入的pubsub其本质是一个对象
这里我们首先介绍一下,他的相关API:
消息的发布语法:
pubsub.publish('name',value)
消息的订阅语法:
PubSub.subscribe('name',回调方法)
注意:
这里的回调函数有两个形参:
第一个形参代表消息名
第二个形参代表传递的数据
取消订阅的语法:
- 取消指定的订阅
Pubsub.unsubscribe('name')
- 取消所有的订阅
PubSub.clearAllSubscriptions()
代码实操
我们沿用全局事件总线中的代码。仍然是Student组件向School组件发送学生姓名。
组件结构
首先因为School组件是消息的接收方,所以我们先在School组件中进行消息的订阅:
<template>
<div class="demo">
<h2>学校名称:{
{name}}</h2>
<h2>学校地址:{
{address}}</h2>
<hr>
</div>
</template>
<script> import pubsub from 'pubsub-js' export default {
name:'DongBei', data(){
return {
name:'NEFU', address:'哈尔滨', } }, // props:['getSchoolName'], methods:{
studentNameDeliver(name,data){
console.log('School组件已经接收到了来自Studennt组件的学生名称',data) } }, mounted() {
pubsub.subscribe('studentName',this.studentNameDeliver) }, } </script>
<style > .demo {
background-color: yellow; } </style>
然后我们再在Student组件中进行消息的发布:
<template>
<div class="demo">
<h2 class="stu" >学生名称:{
{name}}</h2>
<h2 >学生年纪:{
{age}}</h2>
<button @click="deliverStudentName">把学生名称给School组件</button>
</div>
</template>
<script> import pubsub from 'pubsub-js' export default {
name:'MyStudent', data(){
return {
name:'张三', age:18 } }, methods:{
deliverStudentName(){
pubsub.publish('studentName',this.name) } } } </script>
<style > /*.demo {*/ /* background-color: green;*/ /*}*/ </style>
效果:
最后我们还要进行收尾工作,在School组件中进行消息订阅的解绑:
消息订阅的解绑有点类似与定时器的关闭:
<template>
<div class="demo">
<h2>学校名称:{
{name}}</h2>
<h2>学校地址:{
{address}}</h2>
<hr>
</div>
</template>
<script> import pubsub from 'pubsub-js' export default {
name:'DongBei', data(){
return {
name:'NEFU', address:'哈尔滨', } }, methods:{
studentNameDeliver(name,data){
console.log('School组件已经接收到了来自Studennt组件的学生名称',data) } }, mounted() {
this.pubsubId = pubsub.subscribe('studentName',this.studentNameDeliver) }, beforeDestroy() {
pubsub.unsubscribe(this.pubsubId) } } </script>
<style > .demo {
background-color: yellow; } </style>
注意:按照下图这种写法的话
这里的this是undefined
为了避免出错这里的回调函数,有两种写法:
①methods中写,再引入
②写成箭头函数
总结
消息订阅与发布(pubsub)
一种组件间通信的方式,适用于任意组件间通信。
使用步骤:
安装pubsub:
npm i pubsub-js引入:
import pubsub from 'pubsub-js'接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。
methods(){ demo(data){ ......} } ...... mounted() { this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息 }提供数据:
pubsub.publish('xxx',数据)最好在beforeDestroy钩子中,用
PubSub.unsubscribe(pid)去取消订阅。
边栏推荐
- Uniapp tips - set background music
- [technology development-24]: characteristics of existing IOT communication technology
- 从零开始的基于百度大脑EasyData的多人协同数据标注
- Qt学习18 登录对话框实例分析
- Qt学习23 布局管理器(二)
- RocksDB LRUCache
- Flutter dynamic | fair 2.5.0 new version features
- Mysql:insert date:sql error [1292] [22001]: data truncation: incorrect date value:
- [机缘参悟-37]:人感官系统的结构决定了人类是以自我为中心
- Spring cup eight school league
猜你喜欢
[email protected]纳米颗粒)|纳米金属有机框架搭载雷帕霉素|科研试剂"/>金属有机骨架材料ZIF-8包载姜黄素([email protected]纳米颗粒)|纳米金属有机框架搭载雷帕霉素|科研试剂
![[how to solve FAT32 when the computer is inserted into the U disk or the memory card display cannot be formatted]](/img/95/09552d33d2a834af4d304129714775.png)
[how to solve FAT32 when the computer is inserted into the U disk or the memory card display cannot be formatted]

使用Tensorflow进行完整的深度神经网络CNN训练完成图片识别案例2

3D vision - 2 Introduction to pose estimation - openpose includes installation, compilation and use (single frame, real-time video)

解决MySql 1045 Access denied for user ‘root‘@‘localhost‘ (using password: YES)

Go language web development series 28: solve cross domain access of CORS with gin contrib / CORS

Flutter dynamic | fair 2.5.0 new version features

How to use lxml to judge whether the website announcement is updated

Implementation of Muduo accept connection, disconnection and sending data

Solve MySQL 1045 access denied for user 'root' @ 'localhost' (using password: yes)
随机推荐
When updating mysql, the condition is a query
静态链表(数组的下标代替指针)
Leetcode-1175. Prime Arrangements
Depth and breadth first traversal of tree (regardless of binary tree)
Another industry has been broken by Chinese chips. No wonder the leading analog chip companies in the United States have cut prices and sold off
[combinatorics] permutation and combination (two counting principles, examples of set permutation | examples of set permutation and circle permutation)
Uniapp tips - set background music
Static linked list (subscript of array instead of pointer)
Go language web development series 28: solve cross domain access of CORS with gin contrib / CORS
MySQL 数据处理值增删改
GoLand 2021.2 configure go (go1.17.6)
MySQL data processing value addition, deletion and modification
Qt学习21 Qt 中的标准对话框(下)
Using registered classes to realize specific type matching function template
全面发展数字经济主航道 和数集团积极推动UTONMOS数藏市场
[technology development-24]: characteristics of existing IOT communication technology
IBEM mathematical formula detection data set
The shadow of the object at the edge of the untiy world flickers, and the shadow of the object near the far point is normal
Qt学习24 布局管理器(三)
Qt学习18 登录对话框实例分析

