当前位置:网站首页>消息订阅与发布
消息订阅与发布
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)去取消订阅。
边栏推荐
- pytorch 载入历史模型时更换gpu卡号,map_location设置
- [combinatorics] permutation and combination (two counting principles, examples of set permutation | examples of set permutation and circle permutation)
- Solve MySQL 1045 access denied for user 'root' @ 'localhost' (using password: yes)
- Using registered classes to realize specific type matching function template
- KEIL5出现中文字体乱码的解决方法
- Summary of common error reporting problems and positioning methods of thrift
- [机缘参悟-37]:人感官系统的结构决定了人类是以自我为中心
- 金属有机骨架MOFs装载非甾体类抗炎药物|ZIF-8包裹普鲁士蓝负载槲皮素(制备方法)
- Leetcode-1175.Prime Arrangements
- GoLand 2021.2 configure go (go1.17.6)
猜你喜欢

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

Installation impression notes

Bidirectional linked list (we only need to pay attention to insert and delete functions)

Unable to stop it, domestic chips have made another breakthrough, and some links have reached 4nm

Go language unit test 3: go language uses gocovey library to do unit test

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

SQL Injection (GET/Select)

NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线

Ocean CMS vulnerability - search php

3D视觉——2.人体姿态估计(Pose Estimation)入门——OpenPose含安装、编译、使用(单帧、实时视频)
随机推荐
Dynamic programming 01 knapsack and complete knapsack
Richview trvstyle liststyle list style (bullet number)
Mycms we media mall v3.4.1 release, user manual update
[understanding by chance-37]: the structure of human sensory system determines that human beings are self-centered
Father and basketball
php 迷宫游戏
SQL Injection (POST/Search)
Go: send the get request and parse the return JSON (go1.16.4)
Screenshot of the operation steps of upload labs level 4-level 9
Qt学习21 Qt 中的标准对话框(下)
PHP maze game
Golang — template
Failure of vector insertion element iterator in STL
Shell timing script, starting from 0, CSV format data is regularly imported into PostgreSQL database shell script example
使用tensorflow进行完整的DNN深度神经网络CNN训练完成图片识别案例
Unity Render Streaming通过Js与Unity自定义通讯
JS general form submission 1-onsubmit
User and group command exercises
JVM family - overview, program counter day1-1
RichView TRVStyle ListStyle 列表样式(项目符号编号)

