谈谈 Vue 事件机制,并手写$on、$off、$emit、$once
参考答案
事件机制
Vue 2 的组件事件是自建发布订阅,与 DOM 事件独立:
- 每个实例有
this._events = {}(事件名 → 回调数组); $onpush、$emit依次调用、$off移除、$once包一层只执行一次;- 不冒泡:子组件 emit 只通知父组件,不像 DOM 事件沿树冒泡;
- 模板
@xxx编译成on: { xxx: handler },挂到vnode.data.on,updateDOMListeners在 patch 时绑定/解绑。
手写
Vue.prototype.$on = function (event, fn) {
const vm = this
if (Array.isArray(event)) { event.forEach(e => vm.$on(e, fn)); return vm }
;(vm._events[event] || (vm._events[event] = [])).push(fn)
return vm
}
Vue.prototype.$once = function (event, fn) {
const vm = this
function on() { vm.$off(event, on); fn.apply(vm, arguments) }
on.fn = fn // 让 $off(event, fn) 能找到包装函数
vm.$on(event, on)
return vm
}
Vue.prototype.$emit = function (event) {
const vm = this
let cbs = vm._events[event]
if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs // 拷贝,防止回调内 $off 改变数组
const args = toArray(arguments, 1)
cbs.forEach(cb => { try { cb.apply(vm, args) } catch (e) { handleError(e, vm, event) } })
}
return vm
}
Vue.prototype.$off = function (event, fn) {
const vm = this
if (!arguments.length) { vm._events = Object.create(null); return vm }
if (Array.isArray(event)) { event.forEach(e => vm.$off(e, fn)); return vm }
const cbs = vm._events[event]
if (!cbs) return vm
if (!fn) { vm._events[event] = null; return vm }
let i = cbs.length
while (i--) { if (cbs[i] === fn || cbs[i].fn === fn) { cbs.splice(i, 1); break } }
return vm
}
细节
$once要挂on.fn,否则精确解绑找不到;$emit遍历前拷贝数组,避免回调内解绑导致跳过;- 事件不冒泡,跨层通信要逐层 emit 或用 provide/inject、事件总线;
- Vue 3 移除了
$on/$off/$once,只保留$emit(配合emits声明),跨组件用mitt; - 组件
v-on的监听器在销毁时由 patch 自动解绑。