当前位置:网站首页>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-js
introduce :
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 .
边栏推荐
- 全面发展数字经济主航道 和数集团积极推动UTONMOS数藏市场
- 金属有机骨架MOFs装载非甾体类抗炎药物|ZIF-8包裹普鲁士蓝负载槲皮素(制备方法)
- Record 405 questions about bank callback post request
- Leetcode-1175. Prime Arrangements
- Unity render streaming communicates with unity through JS
- Nucleic acid modified metal organic framework drug carrier | pcn-223 metal organic framework encapsulated ad adamantane | zif-8 encapsulated adriamycin (DOX)
- Shell timing script, starting from 0, CSV format data is regularly imported into PostgreSQL database shell script example
- 从零开始的基于百度大脑EasyData的多人协同数据标注
- PHP maze game
- Implementation of Muduo asynchronous logging
猜你喜欢
[email protected](Fe)|甘草次酸修饰金属有机框架材料UiO-66-NH2(简称UiO-66-NH2-GA)"/>
MIL-100( Fe) 包裹小分子阿司匹林形成[email protected](Fe)|甘草次酸修饰金属有机框架材料UiO-66-NH2(简称UiO-66-NH2-GA)
太阳底下无新事,元宇宙能否更上层楼?
SQL Injection (GET/Select)
Flutter dynamic | fair 2.5.0 new version features
Comprehensively develop the main channel of digital economy and digital group, and actively promote the utonmos digital Tibet market
解决MySql 1045 Access denied for user ‘root‘@‘localhost‘ (using password: YES)
FPGA测试方法以Mentor工具为例
Installation impression notes
[technology development-24]: characteristics of existing IOT communication technology
Flutter dynamic | fair 2.5.0 new version features
随机推荐
Bidirectional linked list (we only need to pay attention to insert and delete functions)
JS new challenges
Dynamic programming 01 knapsack and complete knapsack
Qt学习25 布局管理器(四)
Unable to stop it, domestic chips have made another breakthrough, and some links have reached 4nm
JS continues to explore...
Replace the GPU card number when pytorch loads the historical model, map_ Location settings
HALCON联合C#检测表面缺陷——HALCON例程autobahn
JVM系列——概述,程序计数器day1-1
Stack application (balancer)
Shell timing script, starting from 0, CSV format data is regularly imported into PostgreSQL database shell script example
SQL Injection (GET/Search)
C language standard IO function sorting
QT learning 19 standard dialog box in QT (top)
Rasp implementation of PHP
SQL Injection (AJAX/JSON/jQuery)
PhpMyAdmin stage file contains analysis traceability
JVM family - overview, program counter day1-1
[技術發展-24]:現有物聯網通信技術特點
【BW16 应用篇】安信可BW16模组与开发板更新固件烧录说明