当前位置:网站首页>消息订阅与发布
消息订阅与发布
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)
去取消订阅。
边栏推荐
- Unity Render Streaming通过Js与Unity自定义通讯
- User and group command exercises
- Ocean CMS vulnerability - search php
- 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
- MySQL 数据增删改查综合案例
- 又一个行业被中国芯片打破空白,难怪美国模拟芯片龙头降价抛售了
- Thrift threadmanager and three monitors
- [combinatorics] permutation and combination (two counting principles, examples of set permutation | examples of set permutation and circle permutation)
- Spring cup eight school league
- Logback log sorting
猜你喜欢
When updating mysql, the condition is a query
UiO-66-COOH装载苯达莫司汀|羟基磷灰石( HA) 包裹MIL-53(Fe)纳米粒子|装载黄芩苷锰基金属有机骨架材料
Go language unit test 4: go language uses gomonkey to test functions or methods
Installation impression notes
Qt学习20 Qt 中的标准对话框(中)
Mysql:insert date:SQL 错误 [1292] [22001]: Data truncation: Incorrect date value:
Unity embeddedbrowser browser plug-in event communication
How to use lxml to judge whether the website announcement is updated
[quantitative trading] permanent portfolio, turtle trading rules reading, back testing and discussion
RocksDB LRUCache
随机推荐
Use vscode to view hex or UTF-8 codes
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
Spring cup eight school league
JVM系列——概述,程序计数器day1-1
Bidirectional linked list (we only need to pay attention to insert and delete functions)
Golang — template
Function calling convention
Stack application (balancer)
栈应用(平衡符)
Richview trvstyle liststyle list style (bullet number)
SQL Injection (POST/Search)
挡不住了,国产芯片再度突进,部分环节已进到4nm
Record 405 questions about bank callback post request
logback日志的整理
JVM family - overview, program counter day1-1
Qt学习25 布局管理器(四)
Uniapp tips - set background music
php 迷宫游戏
Qt学习18 登录对话框实例分析
pytorch 载入历史模型时更换gpu卡号,map_location设置