当前位置:首页 > VUE

eventbus vue实现

2026-01-07 07:21:59VUE

EventBus 实现原理

EventBus 是一种发布/订阅模式,用于 Vue 组件间的通信。核心是通过一个中央事件总线管理事件监听和触发。

创建 EventBus

在 Vue 项目中创建一个独立的 EventBus 实例:

// event-bus.js
import Vue from 'vue';
export const EventBus = new Vue();

发送事件

在需要发送事件的组件中,通过 $emit 触发事件并传递数据:

eventbus vue实现

// ComponentA.vue
import { EventBus } from './event-bus.js';

EventBus.$emit('event-name', { data: 'some data' });

监听事件

在需要接收事件的组件中,通过 $on 监听事件并处理数据:

// ComponentB.vue
import { EventBus } from './event-bus.js';

EventBus.$on('event-name', (data) => {
  console.log('Received data:', data);
});

移除监听

为避免内存泄漏,在组件销毁时移除事件监听:

eventbus vue实现

// ComponentB.vue
beforeDestroy() {
  EventBus.$off('event-name');
}

全局 EventBus

若需全局使用,可将 EventBus 挂载到 Vue 原型上:

// main.js
import Vue from 'vue';
import App from './App.vue';

Vue.prototype.$eventBus = new Vue();

new Vue({
  render: h => h(App),
}).$mount('#app');

使用时直接通过 this.$eventBus 访问:

// 发送事件
this.$eventBus.$emit('global-event');

// 监听事件
this.$eventBus.$on('global-event', () => {});

注意事项

  • 避免过度使用 EventBus,复杂场景建议使用 Vuex。
  • 确保及时移除监听,防止内存泄漏。
  • 事件命名建议使用常量或统一前缀,避免冲突。

替代方案

对于简单场景,也可直接使用 Vue 内置的 $emit$on

// 父组件监听子组件事件
<child-component @custom-event="handleEvent" />

// 子组件触发事件
this.$emit('custom-event', data);

标签: eventbusvue
分享给朋友:

相关文章

vue实现全文检索

vue实现全文检索

Vue 实现全文检索的方法 客户端全文检索(适用于小型数据集) 使用 flexsearch 或 lunr.js 等轻量级库实现前端全文检索: import FlexSearch from 'fle…

vue实现aop切面

vue实现aop切面

Vue 实现 AOP 切面编程的方法 在 Vue 中实现 AOP(面向切面编程)可以通过多种方式,以下是几种常见的实现方法: 使用 Vue 混入(Mixins) Vue 的混入机制可以用于实现横切…

vue实现头像剪切

vue实现头像剪切

Vue 实现头像剪切的实现方法 使用 vue-cropperjs 库 vue-cropperjs 是一个基于 cropperjs 的 Vue 组件,专门用于图片裁剪。安装方式如下: npm inst…

vue实现多选联动

vue实现多选联动

vue实现多选联动的方法 使用v-model绑定数组 在Vue中,可以通过v-model绑定一个数组来实现多选联动。当复选框被选中或取消选中时,数组会自动更新。 <template>…

vue怎么实现动画

vue怎么实现动画

Vue 动画实现方法 Vue 提供了多种方式实现动画效果,包括内置过渡系统、第三方库集成以及 CSS 动画。以下是常见实现方法: 使用 Vue 过渡系统 通过 <transition>…

vue实现好友列表

vue实现好友列表

实现好友列表的Vue组件 数据准备 在Vue组件的data中定义好友列表数据,通常是一个数组对象,每个对象包含好友的基本信息如ID、头像、昵称等。 data() { return {…