轻量级事件通信神器 mitt
什么是 Mitt?
- 极小体积:压缩后不足 200 字节,是一个真正的“微”型库
- 无依赖:纯 JavaScript 实现,不依赖任何其他库,适用于浏览器(支持 IE9+)及 Node.js
- 功能简明:提供
on、off、emit和all.clear()四个核心方法,API 学习成本极低 - 支持 TypeScript:可以使用泛型加强类型安全,不传递正确类型将触发类型错误
核心用法示例
import mitt from 'mitt';
// 创建事件发射器实例
const emitter = mitt();
// 监听单个事件
emitter.on('foo', e => console.log('foo', e));
// 通配符监听所有事件
emitter.on('*', (type, e) => console.log('Event:', type, e));
// 发射事件
emitter.emit('foo', { a: 'b' });
// 移除监听器
emitter.off('foo', handler);
// 清除所有监听器
emitter.all.clear();
使用 TypeScript 时,你还能这样写:
type Events = { foo: string; bar?: number };
const emitter = mitt<Events>();
emitter.on('foo', (e) => { /* e 推断为 string */ });
emitter.emit('foo', 42); // 会报错:类型不匹配
使用场景与最佳实践
在 Vue 3 或 React 中应用中间件
-
Vue 3 中可使用 Mitt 实现组件间通信(替代 Event Bus),通过全局或局部 emitter 轻松传播消息
-
React 中也适用于跨组件传递事件,结构依旧清晰简洁
注意事项
-
适当使用,避免滥用
对于大型复杂应用或状态密集型逻辑,推荐使用专门的状态管理工具(如 Vuex 或 Pinia)
可以加入我们的扣扣技术群(651706395),互相交流!

浙公网安备 33010602011771号