当前位置:网站首页>Message subscription and publishing
Message subscription and publishing
2022-07-03 14:00:00 【18-year-old hates programming】
List of articles
principle
The subscription and publication of messages can also realize the communication between any two components
There are two steps :
- Subscribe to news
- Release the news
Next, we will understand its steps through an example :
Now we want to implement components A And C Communication between ( Suppose it's a component C Send data to A Components ):
- First component A To subscribe to a message ( Let's assume that this message is called demo)
- Then we will make a callback ( Let's assume that the name of this callback is test)
- Components C Send a message , And carry the data ( We will also name this message demo)
- C Once the component releases the message , because A The component subscribed to this message , So the corresponding callback function will be executed , The data is passed to A Components .
So the message name is very important , What was your name when you subscribed , What was your name when you released it .
Native js It is not easy to subscribe and publish messages . So we usually use the third-party library to complete this function .
What I'm using here is pubsub.js, It can subscribe and publish messages in any framework .
Grammatical annotation
First we install pubsub.js:
npm i pubsub-js
Introduce grammar :
import pubsub from 'pubsub.js'
This was introduced pubsub Its essence is an object
Let's first introduce , His relevance API:
Message publishing syntax :
pubsub.publish('name',value)
Message subscription syntax :
PubSub.subscribe('name', The callback method )
Be careful :
The callback function here has two formal parameters :
The first formal parameter represents the message name
The second parameter represents the passed data
Syntax for unsubscribing :
- Cancel the specified subscription
Pubsub.unsubscribe('name')
- Cancel all subscriptions
PubSub.clearAllSubscriptions()
Code implementation
We use the code in the global event bus . Still Student Components to School The component sends the student name .
Component structure
First of all, because School The component is the receiver of the message , So let's start with School Component to subscribe to messages :
<template>
<div class="demo">
<h2> School name :{
{name}}</h2>
<h2> School address :{
{address}}</h2>
<hr>
</div>
</template>
<script> import pubsub from 'pubsub-js' export default {
name:'DongBei', data(){
return {
name:'NEFU', address:' Harbin ', } }, // props:['getSchoolName'], methods:{
studentNameDeliver(name,data){
console.log('School The component has received a message from Studennt Student name of the component ',data) } }, mounted() {
pubsub.subscribe('studentName',this.studentNameDeliver) }, } </script>
<style > .demo {
background-color: yellow; } </style>
Then we'll be in Student Component to publish messages :
<template>
<div class="demo">
<h2 class="stu" > Student name :{
{name}}</h2>
<h2 > Student age :{
{age}}</h2>
<button @click="deliverStudentName"> Give the student's name to School Components </button>
</div>
</template>
<script> import pubsub from 'pubsub-js' export default {
name:'MyStudent', data(){
return {
name:' Zhang San ', age:18 } }, methods:{
deliverStudentName(){
pubsub.publish('studentName',this.name) } } } </script>
<style > /*.demo {*/ /* background-color: green;*/ /*}*/ </style>
effect :
Finally, we have to finish the work , stay School Unbind the message subscription in the component :
The unbinding of message subscription is a bit similar to the closing of timer :
<template>
<div class="demo">
<h2> School name :{
{name}}</h2>
<h2> School address :{
{address}}</h2>
<hr>
</div>
</template>
<script> import pubsub from 'pubsub-js' export default {
name:'DongBei', data(){
return {
name:'NEFU', address:' Harbin ', } }, methods:{
studentNameDeliver(name,data){
console.log('School The component has received a message from Studennt Student name of the component ',data) } }, mounted() {
this.pubsubId = pubsub.subscribe('studentName',this.studentNameDeliver) }, beforeDestroy() {
pubsub.unsubscribe(this.pubsubId) } } </script>
<style > .demo {
background-color: yellow; } </style>
Be careful : According to the following figure
there this yes undefined
To avoid errors, the callback function here , There are two ways of writing :
①methods Write in , To introduce
② Write as arrow function
summary
News subscription and Publishing (pubsub)
A way of communicating between components , It is suitable for communication between any components .
Use steps :
install pubsub:
npm i pubsub-jsintroduce :
import pubsub from 'pubsub-js'receive data :A The component wants to receive data , It's in A Subscribe to messages in components , The callback of the subscription remains A The component itself .
methods(){ demo(data){ ......} } ...... mounted() { this.pid = pubsub.subscribe('xxx',this.demo) // Subscribe to news }Provide data :
pubsub.publish('xxx', data )Best in beforeDestroy In the hook , use
PubSub.unsubscribe(pid)Go unsubscribe .
边栏推荐
- logback日志的整理
- Go language web development series 27: Gin framework: using gin swagger to implement interface documents
- Cross linked cyclodextrin metal organic framework loaded methotrexate slow-release particles | metal organic porous material uio-66 loaded with flavonoid glycosides | Qiyue
- Qt学习24 布局管理器(三)
- Go language web development series 26: Gin framework: demonstrates the execution sequence of code when there are multiple middleware
- mysql中的字段问题
- 怎样删除对象的某个属性或⽅法
- windos 创建cordova 提示 因为在此系统上禁止运行脚本
- 金属有机骨架材料ZIF-8包载姜黄素([email protected]纳米颗粒)|纳米金属有机框架搭载雷帕霉素|科研试剂
- PhpMyAdmin stage file contains analysis traceability
猜你喜欢

FPGA测试方法以Mentor工具为例

Flutter dynamic | fair 2.5.0 new version features

There is nothing new under the sun. Can the meta universe go higher?

Qt学习18 登录对话框实例分析

Use and design of Muduo buffer class

Richview trvstyle liststyle list style (bullet number)

交联环糊精金属有机骨架负载甲氨蝶呤缓释微粒|金属-有机多孔材料UiO-66负载黄酮苷类药物|齐岳

JVM系列——概述,程序计数器day1-1
[email "/>Doxorubicin loaded on metal organic framework MIL-88 DOX | folic acid modified uio-66-nh2 doxorubicin loaded [email

logback日志的整理
随机推荐
QT learning 17 dialog box and its types
The solution of Chinese font garbled code in keil5
Screenshot of the operation steps of upload labs level 4-level 9
MIL-100( Fe) 包裹小分子阿司匹林形成[email protected](Fe)|甘草次酸修饰金属有机框架材料UiO-66-NH2(简称UiO-66-NH2-GA)
page owner特性浅析
Uio-66-cooh loaded bendamostine | hydroxyapatite (HA) coated MIL-53 (FE) nanoparticles | baicalin loaded manganese based metal organic skeleton material
Qt学习24 布局管理器(三)
Go: send the get request and parse the return JSON (go1.16.4)
QT learning 19 standard dialog box in QT (top)
Doxorubicin loaded on metal organic framework MIL-88 DOX | folic acid modified uio-66-nh2 doxorubicin loaded [email
QT learning 23 layout manager (II)
[ACNOI2022]猜数
Go language unit test 5: go language uses go sqlmock and Gorm to do database query mock
[technology development-24]: characteristics of existing IOT communication technology
可编程逻辑器件软件测试
从零开始的基于百度大脑EasyData的多人协同数据标注
Metal organic framework material zif-8 containing curcumin( [email protected] Nanoparticles) | nano metal organic framework carry
SQL Injection (POST/Select)
Unity embeddedbrowser browser plug-in event communication
挡不住了,国产芯片再度突进,部分环节已进到4nm

