当前位置:网站首页>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 .
边栏推荐
- MySQL data processing value addition, deletion and modification
- Mastering the cypress command line options is the basis for truly mastering cypress
- Folic acid modified metal organic framework (zif-8) baicalin loaded metal organic framework composite magnetic material (AU- [email
- [how to earn a million passive income]
- Screenshot of the operation steps of upload labs level 4-level 9
- PhpMyAdmin stage file contains analysis traceability
- C language standard IO function sorting
- 怎样删除对象的某个属性或⽅法
- Qt学习24 布局管理器(三)
- Bidirectional linked list (we only need to pay attention to insert and delete functions)
猜你喜欢

交联环糊精金属有机骨架负载甲氨蝶呤缓释微粒|金属-有机多孔材料UiO-66负载黄酮苷类药物|齐岳
![Mysql:insert date:SQL 错误 [1292] [22001]: Data truncation: Incorrect date value:](/img/2f/33504391a661ecb63d42d75acf3a37.png)
Mysql:insert date:SQL 错误 [1292] [22001]: Data truncation: Incorrect date value:

How to use lxml to judge whether the website announcement is updated

RocksDB LRUCache

【BW16 应用篇】安信可BW16模组与开发板更新固件烧录说明

QT learning 23 layout manager (II)

GoLand 2021.1: rename the go project

Summary of common error reporting problems and positioning methods of thrift

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

小项目(servelt+jsp+mysql+EL+JSTL)完成一个登录功能的Servlet,具有增删改查的操作。实现登录身份验证,防止非法登录,防止多点登录,记住用户名密码功能。
随机推荐
Uniapp skills - scrolling components -1
[556. Next larger element III]
Summary of common error reporting problems and positioning methods of thrift
[how to earn a million passive income]
logback日志的整理
Use vscode to view hex or UTF-8 codes
Qt学习21 Qt 中的标准对话框(下)
Go language web development series 28: solve cross domain access of CORS with gin contrib / CORS
GoLand 2021.2 configure go (go1.17.6)
Flutter dynamic | fair 2.5.0 new version features
Dlopen() implements dynamic loading of third-party libraries
如何使用lxml判断网站公告是否更新
叶酸修饰的金属-有机骨架(ZIF-8)载黄芩苷|金属有机骨架复合磁性材料([email protected])|制备路线
QT learning 21 standard dialog box in QT (Part 2)
Halcon combined with C # to detect surface defects -- Halcon routine autobahn
[understanding by chance-37]: the structure of human sensory system determines that human beings are self-centered
Conversion function and explicit
Unable to stop it, domestic chips have made another breakthrough, and some links have reached 4nm
How to use lxml to judge whether the website announcement is updated
树的深入和广度优先遍历(不考虑二叉树)
