当前位置:首页 > 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循环数组的实现方法 在Vue中循环数组主要通过v-for指令实现,以下是几种常见用法: 基本数组循环 使用v-for指令遍历数组,可以通过(item, index)的语法获取当前项和索引值:…

vue实现上移下移插件

vue实现上移下移插件

实现上移下移功能的 Vue 插件 在 Vue 中实现列表项的上移和下移功能,可以通过自定义指令或组件封装的方式完成。以下是两种常见实现方式: 基于数组操作的通用方法 通过操作数组索引实现元素位置交换…

实现vue组件

实现vue组件

Vue 组件的基本实现 Vue 组件是 Vue.js 的核心特性之一,允许将 UI 拆分为独立、可复用的模块。以下是实现 Vue 组件的几种方式: 单文件组件 (SFC) 使用 .vue 文件格式…

vue实现bootstrap

vue实现bootstrap

Vue 中集成 Bootstrap 的方法 在 Vue 项目中集成 Bootstrap 可以通过以下方式实现,涵盖样式、组件和交互功能。 安装 Bootstrap 依赖 通过 npm 或 yarn…

vue实现滑块

vue实现滑块

Vue 实现滑块组件的方法 使用原生 HTML 和 Vue 指令 通过 Vue 的 v-model 和事件监听实现基础滑块功能。创建一个包含 input 元素的组件,类型设置为 range,并绑定到…

vue实现看板

vue实现看板

Vue 实现看板功能 使用 Vue 实现看板功能可以通过组件化开发、状态管理和拖拽库结合完成。以下是一个完整的实现方案: 基础项目结构 src/ ├── components/ │ ├── K…