当前位置:网站首页>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 .
边栏推荐
- HALCON联合C#检测表面缺陷——HALCON例程autobahn
- logback日志的整理
- Use docker to build sqli lab environment and upload labs environment, and the operation steps are provided with screenshots.
- Windos creates Cordova prompt because running scripts is prohibited on this system
- jvm-运行时数据区
- [understanding by chance-37]: the structure of human sensory system determines that human beings are self-centered
- Go language web development series 25: Gin framework: using MD5 to verify the signature for the interface station
- 28:第三章:开发通行证服务:11:在配置文件中定义属性,然后在代码中去获取;
- Selenium browser (1)
- [développement technologique - 24]: caractéristiques des technologies de communication Internet des objets existantes
猜你喜欢

3D vision - 2 Introduction to pose estimation - openpose includes installation, compilation and use (single frame, real-time video)

Go: send the get request and parse the return JSON (go1.16.4)
[email protected])|制备路线"/>叶酸修饰的金属-有机骨架(ZIF-8)载黄芩苷|金属有机骨架复合磁性材料([email protected])|制备路线

【吉林大学】考研初试复试资料分享

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

Flutter dynamic | fair 2.5.0 new version features

Metal organic framework MOFs loaded with non steroidal anti-inflammatory drugs | zif-8 wrapped Prussian blue loaded quercetin (preparation method)

Go language web development series 26: Gin framework: demonstrates the execution sequence of code when there are multiple middleware

掌握Cypress命令行选项,是真正掌握Cypress的基础

金属有机骨架MOFs装载非甾体类抗炎药物|ZIF-8包裹普鲁士蓝负载槲皮素(制备方法)
随机推荐
Example analysis of QT learning 18 login dialog box
[combinatorics] permutation and combination (two counting principles, examples of set permutation | examples of set permutation and circle permutation)
Use docker to build sqli lab environment and upload labs environment, and the operation steps are provided with screenshots.
JS general form submission 1-onsubmit
记录关于银行回调post请求405 问题
Record 405 questions about bank callback post request
SQL Injection (POST/Search)
JS continues to explore...
Implementation of Muduo accept connection, disconnection and sending data
Doxorubicin loaded on metal organic framework MIL-88 DOX | folic acid modified uio-66-nh2 doxorubicin loaded [email
PHP maze game
Leetcode-1175.Prime Arrangements
从零开始的基于百度大脑EasyData的多人协同数据标注
HALCON联合C#检测表面缺陷——HALCON例程autobahn
Go language web development series 25: Gin framework: using MD5 to verify the signature for the interface station
selenium 浏览器(1)
[acnoi2022] guess numbers
Mastering the cypress command line options is the basis for truly mastering cypress
28:第三章:开发通行证服务:11:在配置文件中定义属性,然后在代码中去获取;
Sequence table (implemented in C language)

