当前位置:网站首页>全局事件总线
全局事件总线
2022-07-28 05:19:00 【小白鼠零号】
假设App中有组件A、B、C、D。App外有个不属于任何组件的X。我们想实现D将数据666传递给组件A。
首先,A给X绑定个名叫demo的自定义事件,事件的回调函数在组件A中。
其次,组件D只要触发X身上的demo事件即可。
因为:X身上的demo被触发,那么demo事件所对应的回调也被执行。
如果,D想将8传递给组件B,该怎么办呢?
首先,B给X绑定个名叫test的自定义事件,事件的回调函数在组件B中。
其次,组件D只要触发X身上的test事件即可。
- X应该在哪里添加呢?
首先,X应该能被所有的组件所看到(使用),那么X应该在Vue的原型对象处添加。
在main.js中:
// 在Vue的原型对象处添加X
Vue.prototype.x = {
a:1,b:2}
但是,上面的代码就写死了。我们应该
// 构建一个VueComponent
const Demo = Vue.extend({
})
// d是组件的实例对象vc,而vc能调用$on,$off,$emit
const d = new Demo()
// 在Vue的原型对象处添加X
Vue.prototype.x = d
我们还可以用vm来完成,下面的this就代表vm实例,而且是在项目生产之前完成的。
new Vue({
……
beforeCreate(){
Vue.prototype.x = this
}
})
总结:
标准的写法为:
new Vue({
……
beforeCreate(){
Vue.prototype.$bus = this //安装全局事件总线
}
})
实例解析
前提:
App中包含了组件Student和组件School,属于同级组件。我们想让Student发送一个666给School。
- 首先,在main.js中写好X(后面用标准写法$bus来代替)
- 其次,School想获取Student中的内容,那么就给X绑定事件hello。
- 最后,Student里面触发事件hello就可以。
Student中:
设计一个按钮,给按钮一个点击事件,点击触发sendStudentName(),进而触发hello
触发hello事件,并传递666
<template>
<div>
<button @click="sendStudentName">把学生名给School组件</button>
</div>
</template>
……
methods:{
sendStudentName(){
this.$bus.$emit('hello',666)
}
School中:
School在载入时就绑定事件hello,获取的值是data
mounted(){
this.$bus.$on('hello',(data)=>{
console.log('我是School组件,收到了数据',data)
}),
beforeDestroy(){
this.$bus.$off('hello') //解绑hello事件
}
边栏推荐
猜你喜欢
随机推荐
排序之插入排序
Mysql database index (InnoDB engine)
C语言回顾(修饰词篇)
TopK问题
js数据类型检测与修改检测
How Visio accurately controls the size, position and angle of graphics
Sequence table OJ topic
openjudge:找出全部子串位置
异步编程Promise
openjudge:矩阵乘法
Canvas绘图2
冶金物理化学复习 ---- 气固反应动力学
The Monte Carlo method solves the PI and draws points with turtle, and completes the progress bar problem
Openjudge: filter extra spaces
环形链表问题
Oracle create table, delete table, modify table (add field, modify field, delete field) statement summary
冶金物理化学复习 --- 气-液相反应动力学
冶金物理化学复习 --- 复杂反应的速率方程
Review of metallurgical physical chemistry -- cathodic polarization, overpotential, anode and anode process in metal electrodeposition
Mabtis (I) basic use of framework









