CustomEvent 是跨框架通信的通用方案,通过独立 EventTarget 实例作为事件总线,统一事件名与数据结构,各框架组件按生命周期绑定/解绑监听器,并支持带唯一 ID 的异步响应模式。

CustomEvent 是浏览器原生的事件机制,不依赖任何框架,天然适合跨 React、Vue、Vanilla JS 组件通信。关键在于统一事件总线(event bus)和规范事件名、数据结构,避免框架生命周期干扰。
创建全局事件总线
用一个独立的 EventTarget 实例作为中央消息通道,所有框架组件都向它 dispatch 或 addEventListener,避开 DOM 树限制和框架封装层。
- 在 单独文件(如
eventBus.js)中定义:
export const eventBus = new EventTarget();
- 各框架组件直接 import 使用,无需额外初始化或挂载到 DOM 节点上
- 避免用
window或document发事件——可能被其他脚本干扰,且 Vue 3 的 Shadow DOM 场景下不可靠
发送事件:统一使用 CustomEvent 构造器
确保 payload 可序列化、结构清晰,便于多框架消费。
- 推荐写法(含类型提示和可选 detail):
// React 组件内
import { eventBus } from './eventBus';
eventBus.dispatchEvent(
new CustomEvent('user:login', {
detail: { id: 123, name: 'Alice' }
})
);
- Vue 2/3 中同样适用(setup 或 options API 均可):
// Vue 3 setup
import { eventBus } from './eventBus';
const handleLogin = () => {
eventBus.dispatchEvent(
new CustomEvent('user:login', {
detail: { id: 123, name: 'Alice' }
})
);
};
- Vanilla JS 更简单,直接调用即可
- 注意:不要在
detail中传函数、DOM 节点或 Vue/React 实例,否则其他框架无法安全读取
监听事件:绑定与解绑需匹配生命周期
防止内存泄漏,各框架需在卸载/销毁时移除监听器。
使用 assistant-ui 构建具有可重用线程、运行时、消息组件和模型/提供者适配器的生产级 React 聊天界面。
立即学习“前端免费学习笔记(深入)”;
- React(useEffect 清理):
useEffect(() => {
const handler = (e) => console.log('收到登录信息:', e.detail);
eventBus.addEventListener('user:login', handler);
return () => eventBus.removeEventListener('user:login', handler);
}, []);
- Vue 3(onUnmounted):
import { onUnmounted } from 'vue';
import { eventBus } from './eventBus';
const handler = (e) => console.log('收到登录信息:', e.detail);
eventBus.addEventListener('user:login', handler);
onUnmounted(() => {
eventBus.removeEventListener('user:login', handler);
});
- Vanilla JS(手动管理):在组件 destroy 或元素 remove 时调用 removeEventListener
- 强烈建议给 handler 命名(而非匿名函数),否则无法精确 remove
进阶:支持异步响应与错误处理
若需要“请求-响应”模式(如 A 发起查询,B 返回结果),可用 Promise + 唯一 ID 配合 CustomEvent 实现。
- 发送方生成唯一 request ID,并监听带该 ID 的响应事件:
const requestId = Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
eventBus.dispatchEvent(
new CustomEvent('api:fetch-user', {
detail: { userId: 456, requestId }
})
);
const responseHandler = (e) => {
if (e.detail?.requestId === requestId) {
console.log('响应数据:', e.detail.data);
eventBus.removeEventListener('api:fetch-user:response', responseHandler);
}
};
eventBus.addEventListener('api:fetch-user:response', responseHandler);
- 接收方处理后 dispatch 同名响应事件(如
api:fetch-user:response),携带相同requestId - 这种方式绕过框架间 Promise 传递限制,也兼容同步/异步逻辑
不复杂但容易忽略:事件命名建议用冒号分隔作用域(如 auth:logout、cart:item:add),避免冲突;所有团队成员共用同一份事件文档,比写适配器更轻量可靠。

















