当前位置:网站首页>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 .
边栏推荐
- 交联环糊精金属有机骨架负载甲氨蝶呤缓释微粒|金属-有机多孔材料UiO-66负载黄酮苷类药物|齐岳
- FPGA测试方法以Mentor工具为例
- php 迷宫游戏
- [技術發展-24]:現有物聯網通信技術特點
- Go language unit test 3: go language uses gocovey library to do unit test
- There is nothing new under the sun. Can the meta universe go higher?
- 金属有机骨架MOFs装载非甾体类抗炎药物|ZIF-8包裹普鲁士蓝负载槲皮素(制备方法)
- QT learning 23 layout manager (II)
- Metal organic framework (MOFs) antitumor drug carrier | pcn-223 loaded with metronidazole | uio-66 loaded with ciprofloxacin hydrochloride( QT learning 21 standard dialog box in QT (Part 2)
猜你喜欢
QT learning 17 dialog box and its types
MySQL 数据处理值增删改
Mysql:insert date:SQL 错误 [1292] [22001]: Data truncation: Incorrect date value:
jvm-运行时数据区
全局事件总线
Common network state detection and analysis tools
又一个行业被中国芯片打破空白,难怪美国模拟芯片龙头降价抛售了
Mysql:insert date:sql error [1292] [22001]: data truncation: incorrect date value:
NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线
Qt学习24 布局管理器(三)
随机推荐
Formation of mil-100 (FE) coated small molecule aspirin [email protected] (FE) | glycyrrhetinic acid modified metal organ
PhpMyAdmin stage file contains analysis traceability
Function calling convention
Logback log sorting
Richview trvstyle liststyle list style (bullet number)
NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
Unity embeddedbrowser browser plug-in event communication
如何使用lxml判断网站公告是否更新
Go language web development series 26: Gin framework: demonstrates the execution sequence of code when there are multiple middleware
Go language web development series 25: Gin framework: using MD5 to verify the signature for the interface station
金属有机骨架MOFs装载非甾体类抗炎药物|ZIF-8包裹普鲁士蓝负载槲皮素(制备方法)
QT learning 19 standard dialog box in QT (top)
There is nothing new under the sun. Can the meta universe go higher?
Failure of vector insertion element iterator in STL
Comprehensive case of MySQL data addition, deletion, modification and query
使用vscode查看Hex或UTF-8编码
[机缘参悟-37]:人感官系统的结构决定了人类是以自我为中心
Solve MySQL 1045 access denied for user 'root' @ 'localhost' (using password: yes)
Stack application (balancer)
JS continues to explore...