当前位置:网站首页>消息订阅与发布
消息订阅与发布
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)去取消订阅。
边栏推荐
- Heap structure and heap sort heapify
- Replace the GPU card number when pytorch loads the historical model, map_ Location settings
- 从零开始的基于百度大脑EasyData的多人协同数据标注
- [développement technologique - 24]: caractéristiques des technologies de communication Internet des objets existantes
- JVM系列——概述,程序计数器day1-1
- Libuv Library - Design Overview (Chinese version)
- Qt学习22 布局管理器(一)
- Sequence table (implemented in C language)
- Richview trvstyle liststyle list style (bullet number)
- Qt学习18 登录对话框实例分析
猜你喜欢
[email protected])|制备路线"/>叶酸修饰的金属-有机骨架(ZIF-8)载黄芩苷|金属有机骨架复合磁性材料([email protected])|制备路线

Go language web development series 25: Gin framework: using MD5 to verify the signature for the interface station

Implementation of Muduo asynchronous logging

Students who do not understand the code can also send their own token, which is easy to learn BSC

Conversion function and explicit
![[understanding by chance-37]: the structure of human sensory system determines that human beings are self-centered](/img/06/b71b505c7072d540955fda6da1dc1b.jpg)
[understanding by chance-37]: the structure of human sensory system determines that human beings are self-centered

Go language web development series 26: Gin framework: demonstrates the execution sequence of code when there are multiple middleware

太阳底下无新事,元宇宙能否更上层楼?

Flutter dynamic | fair 2.5.0 new version features

Go language unit test 5: go language uses go sqlmock and Gorm to do database query mock
随机推荐
User and group command exercises
全面发展数字经济主航道 和数集团积极推动UTONMOS数藏市场
Stack application (balancer)
MySQL data processing value addition, deletion and modification
研发团队资源成本优化实践
Qt学习20 Qt 中的标准对话框(中)
[how to solve FAT32 when the computer is inserted into the U disk or the memory card display cannot be formatted]
Go language web development series 30: gin: grouping by version for routing
Unity embeddedbrowser browser plug-in event communication
JVM family - overview, program counter day1-1
Leetcode-1175.Prime Arrangements
Conversion function and explicit
Common network state detection and analysis tools
Using registered classes to realize specific type matching function template
如何使用lxml判断网站公告是否更新
Mycms we media mall v3.4.1 release, user manual update
Ocean CMS vulnerability - search php
Comprehensive case of MySQL data addition, deletion, modification and query
Go language web development series 26: Gin framework: demonstrates the execution sequence of code when there are multiple middleware
IBEM mathematical formula detection data set

