简单实现vue事件机制
Vue 事件机制实现
Vue 的事件机制主要依赖于 $on、$emit 和 $off 方法,用于组件间的通信。以下是简化版的事件总线实现:
1. 创建事件总线
class EventBus {
constructor() {
this.events = {};
}
$on(eventName, callback) {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(callback);
}
$emit(eventName, ...args) {
const callbacks = this.events[eventName];
if (callbacks) {
callbacks.forEach(cb => cb(...args));
}
}
$off(eventName, callback) {
if (!eventName) {
this.events = {};
return;
}
if (!callback) {
delete this.events[eventName];
return;
}
const callbacks = this.events[eventName];
if (callbacks) {
this.events[eventName] = callbacks.filter(cb => cb !== callback);
}
}
}
const bus = new EventBus();
2. 使用示例
// 监听事件
bus.$on('message', (text) => {
console.log('Received:', text);
});
// 触发事件
bus.$emit('message', 'Hello World');
// 移除事件
const handler = (text) => console.log('Handler:', text);
bus.$on('message', handler);
bus.$off('message', handler);
3. 组件间通信
// 组件A
bus.$emit('update-data', { id: 1 });
// 组件B
bus.$on('update-data', (payload) => {
console.log('Data updated:', payload);
});
4. 注意事项
- 事件名建议使用常量避免拼写错误
- 及时移除无用的事件监听防止内存泄漏
- 复杂场景建议使用 Vuex 替代事件总线
这个简化实现包含了 Vue 事件系统的核心功能,可以直接在项目中使用或作为学习参考。实际 Vue 源码中的实现会更复杂,包含更多边界情况处理。






