当前位置:网站首页>全局事件总线
全局事件总线
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事件
}
边栏推荐
猜你喜欢
随机推荐
A file upload tool website written by individuals
pytorch 计算模型的GFlops和total params的方法
openjudge:判断字符串是否为回文
DOM窗口相关数据、操作 & BOM操作
Oracle uses SQL to query the field information of a table (field type, length, etc.)
链表中关于快慢指针的oj题
Methods of gflops and total params of pytorch calculation model
Openjudge: find the first character that appears only once
ES6----解构赋值
Use of IO streams
操作文档树
C语言回顾(指针篇)
Review of metallurgical physical chemistry -- Fundamentals of metallurgical reaction kinetics and characteristics of multiphase reaction kinetics
Canvas绘图1
[idea plug-in artifact] teaches you how to set all attributes in an entity class with one click of idea
树莓派WIFI一键连接配置
标准C语言学习总结9
Advanced multithreading: the role and implementation principle of volatile
C语言回顾(可变参数篇)
Custom JSON return data









