兄弟组件传值

https://www.bilibili.com/video/BV1Hu411r7dt/?spm_id_from=333.337.search-card.all.click&vd_source=d87a0cdb006a04b60ce265a9ce85d6af



eventBus可以在全局定义,实现全项目通讯,使用方法也很简单。

1、初始化——全局定义

全局定义,可以将eventBus绑定到vue实例的原型上,也可以直接绑定到window对象上.

//main.js
//方式一
Vue.prototype.$EventBus = new Vue();
//方式二
window.eventBus = new Vue();
2、触发事件

//使用方式一定义时
this.$EventBus.$emit('eventName', param1,param2,...)
//使用方式二定义时
EventBus.$emit('eventName', param1,param2,...)
3、监听事件

//使用方式一定义时
this.$EventBus.$on('eventName', (param1,param2,...)=>{
//需要执行的代码
})
//使用方式二定义时
EventBus.$on('eventName', (param1,param2,...)=>{
//需要执行的代码
})
4、移除监听事件

为了避免在监听时,事件被反复触发,通常需要在页面销毁时移除事件监听。或者在开发过程中,由于热更新,事件可能会被多次绑定监听,这时也需要移除事件监听。

//使用方式一定义时
this.$EventBus.$off('eventName');
//使用方式二定义时
EventBus.$off('eventName');


原文链接:https://blog.csdn.net/qq_26834399/article/details/106387585

posted @ 2022-10-15 13:48  .net&new  阅读(33)  评论(0编辑  收藏  举报