Subscription and publication of Vue messages

introduce

It is used for communication between components, which can realize the communication of any component.
Publish and subscribe mode

use

download

npm i pubsub-js -s

Import, all files used must be imported

import pubsub from 'pubsub-js'

release

pubsub.publish("hello", 666)

subscription

this.d_pid = pubsub.subscribe("hello", (msgName, data) => {
    
    
      console.log("有人发布了hello消息," + msgName + "回调执行了,收到数据:" + data);
      //有人发布了hello消息,hello回调执行了,收到数据:666
})

Subscription parameter explanation

PubSub.subscribe(name,(meg,data)=>{
    
    })
第一个参数是订阅的事件
第二个参数是别人发布了订阅以后执行的函数,接收的meg是事件名字name的值,data是别人发布订阅传递过来的数据

Publish parameter explanation

pubsub.publish(name,data)
第一个参数是发布事件(与订阅事件同名,才能对接)
第二个是传递参数

this.d_pid : As an identifier (it is easy to destroy when it is destroyed)
when the component is destroyed, the subscription event must be cleared in time

Guess you like

Origin blog.csdn.net/qq_45859670/article/details/125210354
Recommended