当前位置:网站首页>消息订阅与发布
消息订阅与发布
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)
去取消订阅。
边栏推荐
- 掌握Cypress命令行选项,是真正掌握Cypress的基础
- Mastering the cypress command line options is the basis for truly mastering cypress
- Qt学习25 布局管理器(四)
- Mobile phones and computers can be used, whole people, spoof code connections, "won't you Baidu for a while" teach you to use Baidu
- Unity Render Streaming通过Js与Unity自定义通讯
- Complete DNN deep neural network CNN training with tensorflow to complete image recognition cases
- php 迷宫游戏
- Summary of common error reporting problems and positioning methods of thrift
- 全面发展数字经济主航道 和数集团积极推动UTONMOS数藏市场
- IBEM mathematical formula detection data set
猜你喜欢
Qt学习21 Qt 中的标准对话框(下)
Unable to stop it, domestic chips have made another breakthrough, and some links have reached 4nm
Go language unit test 5: go language uses go sqlmock and Gorm to do database query mock
NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
Use and design of Muduo buffer class
[email protected])"/>
金属有机骨架(MOFs)抗肿瘤药载体|PCN-223装载甲硝唑|UiO-66包载盐酸环丙沙星([email protected])
Comprehensively develop the main channel of digital economy and digital group, and actively promote the utonmos digital Tibet market
Flutter动态化 | Fair 2.5.0 新版本特性
RocksDB LRUCache
8 Queen question
随机推荐
Using registered classes to realize specific type matching function template
Ocean CMS vulnerability - search php
Software testing is so hard to find, only outsourcing offers, should I go?
[understanding by chance-37]: the structure of human sensory system determines that human beings are self-centered
Mastering the cypress command line options is the basis for truly mastering cypress
Brief analysis of tensorboard visual processing cases
RichView TRVStyle ListStyle 列表样式(项目符号编号)
IBEM 数学公式检测数据集
GoLand 2021.1: rename the go project
Qt学习21 Qt 中的标准对话框(下)
CVPR 2022 | interpretation of 6 excellent papers selected by meituan technical team
[combinatorics] permutation and combination (two counting principles, examples of set permutation | examples of set permutation and circle permutation)
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
Common network state detection and analysis tools
MySQL data processing value addition, deletion and modification
Complete deep neural network CNN training with tensorflow to complete picture recognition case 2
JS general form submission 1-onsubmit
[556. Next larger element III]
Disruptor -- a high concurrency and high performance queue framework for processing tens of millions of levels
How to use lxml to judge whether the website announcement is updated