Vue message subscription and publishing
Remarks: The global event bus is used more, and you only need to know about message subscription and publishing.
- Need to import library: pubsub-js
- Graphical process
- Premise: A component wants to get the content in C component
- Method: A is a subscriber and B is a publisher.
- Process:
A subscribes a message named demo, sets a test function
B publishes it named demo, and attaches the parameter 666 that A wants to get.
Once the demo is released in C, the test function will be executed to get the parameter 666
- Install pubsub-js
npm i pubsub-js
- import the installed library
on the subscribers of the message import
import pubsub from 'pubsub-js'
Vue project analysis of Student & School
- premise:
- School wants to get the student name in Student
- School is the subscriber of the message, and Student is the publisher of the message
2. Code analysis
in School:
# 引入库
import pubsub from 'pubsub-js'
……
# 在School组件挂载时订阅名叫hello的消息,一旦hello消息发布了,就执行里面的函数
mounted(){
pubsub.subscribe('hello',function (){
console.log('有人发布了hello消息,hello消息的回调执行了')
})
Student:
<template>
<div>
<h2>学生姓名:{
{
name}}</h2>
# 点击按钮触发sendStudentName函数
<button @click="sendStudentName">把学生名给School</button>
</div>
</template>
# 引入库
import pubsub from 'pubsub-js'
……
# 在sendStudentName中发布hello消息,并传送666
methods:{
sendStudentName(){
pubsub.publish('hello',666)
}
},
Advanced version:
- Let the data in Student be acquired by School
- Just modify the contents of School in
School:
mounted(){
this.pubId = pubsub.subscribe('hello',(msgName,data)=>{
console.log('有人发布了hello消息,hello消息的回调执行了',msgName,data)
})
},
Among them, msgName comes with Vue by default, and the value is the message name hello. The second is the parameter required by School.