vue事件实现原理
Vue 事件实现原理
Vue 的事件系统基于发布-订阅模式,通过 $on、$emit 等方法实现组件间通信。以下是核心实现原理的分解:
事件注册与存储
Vue 实例内部通过 _events 对象存储事件监听器。调用 $on(event, callback) 时,会将回调函数按事件名存入 _events:
// 简化版实现
Vue.prototype.$on = function (event, fn) {
(this._events[event] || (this._events[event] = [])).push(fn);
};
事件触发
$emit(event, ...args) 会从 _events 中查找对应事件名的回调数组,并依次执行:
Vue.prototype.$emit = function (event, ...args) {
const cbs = this._events[event];
if (cbs) {
cbs.forEach(fn => fn.apply(this, args));
}
};
事件移除
$off(event, callback) 会从 _events 中移除指定事件的回调:
Vue.prototype.$off = function (event, fn) {
if (!arguments.length) {
this._events = Object.create(null);
return;
}
const cbs = this._events[event];
if (!cbs) return;
if (!fn) {
this._events[event] = null;
return;
}
this._events[event] = cbs.filter(cb => cb !== fn);
};
自定义事件与原生事件
- 自定义事件:通过
$emit和$on实现父子组件通信,例如v-on:my-event会被编译为$on('my-event')。 - 原生 DOM 事件:通过
v-on或@绑定到模板时,Vue 会调用原生addEventListener,并在组件销毁时自动解绑。
事件修饰符原理
例如 .stop 和 .prevent 等修饰符会在编译阶段转换为对应的原生事件操作:
// .stop 修饰符的实现逻辑
if (event.stopPropagation) event.stopPropagation();
性能优化
Vue 通过事件缓存机制(如 $once)和自动解绑(组件销毁时调用 $off)避免内存泄漏。







