当前位置:网站首页>Global event bus
Global event bus
2022-07-03 14:00:00 【18-year-old hates programming】
List of articles
Principle analysis
The global event bus can realize the communication between any two components
For example, we now have the following structure :
We want to realize the communication between any two components , There is no lack of an intermediary X( The pink circle in the upper right corner of the picture ). For example, now D Component to A The component transmits a little data , The process is as follows :
- stay A Write some code in the component , to X Bind a custom event ( Suppose the name and name of this custom event are demo)
- stay D Write a piece of code to trigger X Medium demo event
- Bring some data to the past while triggering the event ( For example, let's take a 666)
- At this point, the data comes in the form of parameters A In the component
In the process , It is not difficult for us to find this similar to intermediary X, There are certain requirements :
- He can be seen by all other components
- This X Can call
$on(),$off(),$emit()Other methods
First, we can discuss how to realize the first requirement , We have the following methods :
- Borrow browser objects window, All components must be visible to it ( This method is feasible , But it is not recommended. )
- Since it is visible to all component objects , Then put it in VueComponent On the prototype object of the constructor ( This method is not feasible , because VueComponent Constructor is through Vue.extend from , And every time you get something different VueComponent)
- Based on the previous method , Modify source code , Every new VueComponent, Just mount one X( This method is feasible , But it is not recommended. )
- Using relationships
VueComponent.prototype.__proto__ === Vue.prototype, That is to say, we put X Put it in Vue.prototype On the body , Then all components can find it .( This method is recommended )
Next, we realize the second requirement :
$on(),$off(),$emit()And other methods exist in Vue On the prototype object .
because Vue The properties and methods on the prototype object are for Vue Instance object of (vm) Or the instance object of the component (vc) With , So this X We must create as Vue Instance object of or component .
However, we generally emphasize that there can only be one Vue Instance object of , So we usually use the instance object of the component to replace the mediation X
Code implementation
For example, we now have the following component structure :
We want to realize the communication between two brother components ,Student The component gives the student's name to School Components , Steps are as follows :
① First, create a mediation X
We write in main.js in , because Vue It was introduced at that time
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
const Demo = Vue.extend()
const d = new Demo()
Vue.prototype.talkHelper = d
new Vue({
render: h => h(App),
}).$mount('#app')
② Recipient side (School Components ) To bind events on the mediation
School Components :
<template>
<div class="demo">
<h2> School name :{
{name}}</h2>
<h2> School address :{
{address}}</h2>
<!-- <button @click="getSchoolName(name)"> Click to give the school name to the parent component App</button>-->
<hr>
</div>
</template>
<script> export default {
name:'DongBei', data(){
return {
name:'NEFU', address:' Harbin ', } }, // props:['getSchoolName'], methods:{
studentNameDeliver(name){
console.log('School The component has received a message from Studennt Student name of the component ',name) } }, mounted() {
this.talkHelper.$on('studentName',this.studentNameDeliver) } } </script>
<style > .demo {
background-color: yellow; } </style>
③ Sender side (Student Components ) Call the method on the intermediary
Student Components :
<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> export default {
name:'MyStudent', data(){
return {
name:' Zhang San ', age:18 } }, methods:{
deliverStudentName(){
this.talkHelper.$emit('studentName',this.name) } } } </script>
<style > /*.demo {*/ /* background-color: green;*/ /*}*/ </style>
Final effect :
Code optimization

Create a component instance object separately here vc too troublesome , We might as well use Vue Instance object of vm As an intermediary .

But there is something wrong with this . The time is a little late ! Because the current three lines vm After creation ,App The whole component has been put on the page , That means School On the component mounted It's all done !
Then you go Vue It's too late to put a mediation on the prototype object of !
So the timing of this intermediary is very important , It should be in vm After definition , And in the App Before putting components . So at this time, we thought of using life cycle hooks !

We choose to use beforeCreate(), At this time, the template has not started parsing
So our improved code is as follows :
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
// const Demo = Vue.extend()
// const d = new Demo()
//
// Vue.prototype.talkHelper = d
new Vue({
render: h => h(App),
beforeCreate() {
Vue.prototype.talkHelper = this
}
}).$mount('#app')
This mediation is actually the global event bus , We usually use $bus To mark
That is to say, the above code should be written as :
There is another point of attention : Before the component is destroyed , We should unbind the events bound to the global event bus !
In the custom event, we say that unbinding is optional , Because when the component is destroyed and dies , The custom events on it will naturally disappear . But the global event bus here always exists , Even if one component is destroyed , But the events bound to the global event bus are still , This will cause waste of resources . So here we recommend : Before the component is destroyed , We should unbind the events bound to the global event bus
We use beforeDestroy() Lifecycle hooks to perform unbinding operations :
<template>
<div class="demo">
<h2> School name :{
{name}}</h2>
<h2> School address :{
{address}}</h2>
<hr>
</div>
</template>
<script> export default {
name:'DongBei', data(){
return {
name:'NEFU', address:' Harbin ', } }, methods:{
studentNameDeliver(name){
console.log('School The component has received a message from Studennt Student name of the component ',name) } }, mounted() {
this.talkHelper.$on('studentName',this.studentNameDeliver) }, beforeDestroy() {
this.talkHelper.$off('studentName') } } </script>
<style > .demo {
background-color: yellow; } </style>
summary
Global event bus (GlobalEventBus)
A way of communicating between components , It is suitable for communication between any components .
Install the global event bus :
new Vue({ ...... beforeCreate() { Vue.prototype.$bus = this // Install the global event bus ,$bus Is the current application vm }, ...... })Using the event bus :
receive data :A The component wants to receive data , It's in A In the component $bus Binding custom events , The callback of the event remains A The component itself .
methods(){ demo(data){ ......} } ...... mounted() { this.$bus.$on('xxxx',this.demo) }Provide data :
this.$bus.$emit('xxxx', data )
Best in beforeDestroy In the hook , use $off Unbind the events used by the current component .
边栏推荐
- Windos creates Cordova prompt because running scripts is prohibited on this system
- 金属有机骨架MOFs装载非甾体类抗炎药物|ZIF-8包裹普鲁士蓝负载槲皮素(制备方法)
- Go language unit test 5: go language uses go sqlmock and Gorm to do database query mock
- JVM系列——概述,程序计数器day1-1
- 消息订阅与发布
- Installation impression notes
- HALCON联合C#检测表面缺陷——HALCON例程autobahn
- Halcon combined with C # to detect surface defects -- Halcon routine autobahn
- UiO-66-COOH装载苯达莫司汀|羟基磷灰石( HA) 包裹MIL-53(Fe)纳米粒子|装载黄芩苷锰基金属有机骨架材料
- MySQL data processing value addition, deletion and modification
猜你喜欢

Qt学习19 Qt 中的标准对话框(上)

GoLand 2021.1: rename the go project

UiO-66-COOH装载苯达莫司汀|羟基磷灰石( HA) 包裹MIL-53(Fe)纳米粒子|装载黄芩苷锰基金属有机骨架材料
![[bw16 application] instructions for firmware burning of Anxin Ke bw16 module and development board update](/img/b8/31609303fd817c48b6fff7c43f31e5.png)
[bw16 application] instructions for firmware burning of Anxin Ke bw16 module and development board update

太阳底下无新事,元宇宙能否更上层楼?

PhpMyAdmin stage file contains analysis traceability

Using registered classes to realize specific type matching function template

Go language unit test 4: go language uses gomonkey to test functions or methods

QT learning 21 standard dialog box in QT (Part 2)

使用vscode查看Hex或UTF-8编码
随机推荐
Comprehensive case of MySQL data addition, deletion, modification and query
MIL-100( Fe) 包裹小分子阿司匹林形成[email protected](Fe)|甘草次酸修饰金属有机框架材料UiO-66-NH2(简称UiO-66-NH2-GA)
Use and design of Muduo buffer class
PhpMyAdmin stage file contains analysis traceability
Folic acid modified metal organic framework (zif-8) baicalin loaded metal organic framework composite magnetic material (AU- [email
如何使用lxml判断网站公告是否更新
使用vscode查看Hex或UTF-8编码
QT learning 20 standard dialog box in QT (middle)
项目协作的进度如何推进| 社区征文
Complete DNN deep neural network CNN training with tensorflow to complete image recognition cases
Mysql:insert date:sql error [1292] [22001]: data truncation: incorrect date value:
selenium 浏览器(1)
Sequence table (implemented in C language)
QT learning 19 standard dialog box in QT (top)
Formation of mil-100 (FE) coated small molecule aspirin [email protected] (FE) | glycyrrhetinic acid modified metal organ
JS continues to explore...
[技術發展-24]:現有物聯網通信技術特點
小项目(servelt+jsp+mysql+EL+JSTL)完成一个登录功能的Servlet,具有增删改查的操作。实现登录身份验证,防止非法登录,防止多点登录,记住用户名密码功能。
page owner特性浅析
Go language web development series 30: gin: grouping by version for routing
