Vue全局事件总线$bus

2022-08-01 08:55:56

Vue全局事件总线$bus

全局事件总线(GlobalEventBus)

是一种组件间通讯方式,适用于任意组件间通信
可以这样理解,举个小栗子,比如在兄弟组件中进行通讯,组件1要给组件2传递组件1的一个数据,这就可以有几种方法,
最简单想到的就是将组件1数据先传给App组件,再由App组件把数据传递给组件2,这样实现的兄弟间的通信会很麻烦,
那么就可以通过事件总线进行通信,安装事件总线,通过事件回调将数据获取,闲言少叙,往下看

安装事件总线

首先安装全局事件总线
在main.js文件中

//引入Vueimport Vuefrom'vue'//引入Appimport Appfrom'./App.vue'//关闭Vue的生产提示
Vue.config.productionTip=false//创建vmnewVue({el:'#app',render:h=>h(App),beforeCreate(){Vue.prototype.$bus=this//注册全局事件总线}})

其中

beforeCreate(){Vue.prototype.$bus=this//注册全局事件总线}

这段代码就是在注册全局事件总线,将$bus写在Vue的原型上,让它等于this,这个this就是当前应用的vm,如此这个$bus就可以使用$on,$emit,$off来进行绑定事件,触发事件,解绑事件

使用事件总线

接收数据

组件2想要接收数据,就在组件2中给$bus绑定自定义事件,事件的回调留在组件2本身

methods(){demo(data){......}}......mounted(){this.$bus.$on('xxxx',this.demo)}

提供数据

组件1想把数据给出去,就要通过$bus触发组件2在$bus上绑定的自定义事件,将数据给这个自定义事件,因为自定义事件的回调在组件2本身,所以组件2就可以收到数据了

this.$bus.$on.$emit('xxxx',数据)

解绑事件

在哪里绑定的事件就在哪里解绑事件
根据我们贯穿全文的这个组件1给组件2数据这个栗子,在组件2中绑定的事件就要在组件2中解绑事件,
最好在beforeDestroy钩子中,用$off解绑当前组价所用到的事件(注意看好要解绑的事件,不要不小心将全部事件都解绑了)

最后给出一个例子代码

这个例子是兄弟组件Student和School之间进行通信,其中是School收到Student的数据(也就是Student给School发数据)
在这里插入图片描述

main.js

//引入Vueimport Vuefrom'vue'//引入Appimport Appfrom'./App.vue'//关闭Vue的生产提示
Vue.config.productionTip=false//创建vmnewVue({el:'#app',render:h=>h(App),beforeCreate(){Vue.prototype.$bus=this//注册全局事件总线}})

App.vue

<template><divclass="app"><h1>{{msg}}</h1><School/><Student/></div></template><script>import Studentfrom'./components/Student'import Schoolfrom'./components/School'exportdefault{name:'App',components:{School,Student},data(){return{msg:'你好啊!',}}}</script><style>.app{
		background-color: gray;padding: 5px;}</style>

Student.vue

<template><divclass="student"><h2>学生姓名:{{name}}</h2><h2>学生性别:{{sex}}</h2><button @click="sendStudentName">把学生名给School组件</button></div></template><script>exportdefault{name:'Student',data(){return{name:'张三',sex:'男',}},methods:{sendStudentName(){this.$bus.$emit('hello',this.name)}}}</script><style scoped>.student{
		background-color: pink;padding: 5px;
		margin-top: 30px;}</style>

School.vue

<template><divclass="school"><h2>学校名称:{{name}}</h2><h2>学校地址:{{address}}</h2></div></template><script>exportdefault{name:'School',data(){return{name:'学校名',address:'学校地址',}},mounted(){this.$bus.$on('hello',(data)=>{//绑定自定义事件hello,并留下回调函数
				console.log('我收到了来自学生的信息'+data);})},beforeDestroy(){this.$bus.$off('hello')},}</script><style scoped>.school{
		background-color: skyblue;padding: 5px;}</style>
  • 作者:叶鹤
  • 原文链接:https://blog.csdn.net/weixin_45678985/article/details/124536623
    更新时间:2022-08-01 08:55:56