這是 Vue 3.0 進階系列 的第二篇文章,該系列的第一篇文章是 Vue 3.0 進階之指令探祕。本文阿寶哥將以一個簡單的示例爲切入點,帶大家一起一步步揭開自定義事件背後的祕密。
<div id="app"></div>
<script>
const app = Vue.createApp({
template: '<welcome-button v-on:welcome="sayHi"></welcome-button>',
methods: {
sayHi() {
console.log('你好,我是阿寶哥!');
}
}
})
app.component('welcome-button', {
emits: ['welcome'],
template: `
<button v-on:click="$emit('welcome')">
歡迎
</button>
`
})
app.mount("#app")
</script>
在以上示例中,我們先通過 Vue.createApp
方法創建 app
對象,之後利用該對象上的 component
方法註冊全局組件 —— welcome-button 組件。在定義該組件時,我們通過 emits
屬性定義了該組件上的自定義事件。當然用戶點擊 歡迎 按鈕時,就會發出 welcome
事件,之後就會調用 sayHi
方法,接着控制檯就會輸出 你好,我是阿寶哥! 。
雖然該示例比較簡單,但也存在以下 2 個問題:
-
$emit
方法來自哪裏? -
自定義事件的處理流程是什麼?
下面我們將圍繞這些問題來進一步分析自定義事件背後的機制,首先我們先來分析第一個問題。
一、$emit 方法來自哪裏?
使用 Chrome 開發者工具,我們在 sayHi
方法內部加個斷點,然後點擊 歡迎 按鈕,此時函數調用棧如下圖所示:
在上圖右側的調用棧,我們發現了一個存在於 componentEmits.ts
文件中的 emit
方法。但在模板中,我們使用的是 $emit
方法,爲了搞清楚這個問題,我們來看一下 onClick
方法:
由上圖可知,我們的 $emit
方法來自 _ctx
對象,那麼該對象是什麼對象呢?同樣,利用斷點我們可以看到 _ctx
對象的內部結構:
很明顯 _ctx
對象是一個 Proxy
對象,如果你對 Proxy
對象還不瞭解,可以閱讀 你不知道的 Proxy 這篇文章。當訪問 _ctx
對象的 $emit
屬性時,將會進入 get
捕獲器,所以接下來我們來分析 get
捕獲器:
通過 [[FunctionLocation]]
屬性,我們找到了 get
捕獲器的定義,具體如下所示:
// packages/runtime-core/src/componentPublicInstance.ts
export const RuntimeCompiledPublicInstanceProxyHandlers = extend(
{},
PublicInstanceProxyHandlers,
{
get(target: ComponentRenderContext, key: string) {
// fast path for unscopables when using `with` block
if ((key as any) === Symbol.unscopables) {
return
}
return PublicInstanceProxyHandlers.get!(target, key, target)
},
has(_: ComponentRenderContext, key: string) {
const has = key[0] !== '_' && !isGloballyWhitelisted(key)
// 省略部分代碼
return has
}
}
)
觀察以上代碼可知,在 get
捕獲器內部會繼續調用 PublicInstanceProxyHandlers
對象的 get
方法來獲取 key
對應的值。由於 PublicInstanceProxyHandlers
內部的代碼相對比較複雜,這裏我們只分析與示例相關的代碼:
// packages/runtime-core/src/componentPublicInstance.ts
export const PublicInstanceProxyHandlers: ProxyHandler<any> = {
get({ _: instance }: ComponentRenderContext, key: string) {
const { ctx, setupState, data, props, accessCache, type, appContext } = instance
// 省略大部分內容
const publicGetter = publicPropertiesMap[key]
// public $xxx properties
if (publicGetter) {
if (key === '$attrs') {
track(instance, TrackOpTypes.GET, key)
__DEV__ && markAttrsAccessed()
}
return publicGetter(instance)
},
// 省略set和has捕獲器
}
在上面代碼中,我們看到了 publicPropertiesMap
對象,該對象被定義在 componentPublicInstance.ts
文件中:
// packages/runtime-core/src/componentPublicInstance.ts
const publicPropertiesMap: PublicPropertiesMap = extend(Object.create(null), {
$: i => i,
$el: i => i.vnode.el,
$data: i => i.data,
$props: i => (__DEV__ ? shallowReadonly(i.props) : i.props),
$attrs: i => (__DEV__ ? shallowReadonly(i.attrs) : i.attrs),
$slots: i => (__DEV__ ? shallowReadonly(i.slots) : i.slots),
$refs: i => (__DEV__ ? shallowReadonly(i.refs) : i.refs),
$parent: i => getPublicInstance(i.parent),
$root: i => getPublicInstance(i.root),
$emit: i => i.emit,
$options: i => (__FEATURE_OPTIONS_API__ ? resolveMergedOptions(i) : i.type),
$forceUpdate: i => () => queueJob(i.update),
$nextTick: i => nextTick.bind(i.proxy!),
$watch: i => (__FEATURE_OPTIONS_API__ ? instanceWatch.bind(i) : NOOP)
} as PublicPropertiesMap)
在 publicPropertiesMap
對象中,我們找到了 $emit
屬性,該屬性的值爲 $emit: i => i.emit
,即 $emit
指向的是參數 i
對象的 emit
屬性。下面我們來看一下,當獲取 $emit
屬性時,target
對象是什麼:
由上圖可知 target
對象有一個 _
屬性,該屬性的值是一個對象,且該對象含有 vnode
、type
和 parent
等屬性。因此我們猜測 _
屬性的值是組件實例。爲了證實這個猜測,利用 Chrome 開發者工具,我們就可以輕易地分析出組件掛載過程中調用了哪些函數:
在上圖中,我們看到了在組件掛載階段,調用了 createComponentInstance
函數。顧名思義,該函數用於創建組件實例,其具體實現如下所示:
// packages/runtime-core/src/component.ts
export function createComponentInstance(
vnode: VNode,
parent: ComponentInternalInstance | null,
suspense: SuspenseBoundary | null
) {
const type = vnode.type as ConcreteComponent
const appContext =
(parent ? parent.appContext : vnode.appContext) || emptyAppContext
const instance: ComponentInternalInstance = {
uid: uid++,
vnode,
type,
parent,
appContext,
// 省略大部分屬性
emit: null as any,
emitted: null,
}
if (__DEV__) { // 開發模式
instance.ctx = createRenderContext(instance)
} else { // 生產模式
instance.ctx = { _: instance }
}
instance.root = parent ? parent.root : instance
instance.emit = emit.bind(null, instance)
return instance
}
在以上代碼中,我們除了發現 instance
對象之外,還看到了 instance.emit = emit.bind(null, instance)
這個語句。這時我們就找到了 $emit
方法來自哪裏的答案。弄清楚第一個問題之後,接下來我們來分析自定義事件的處理流程。
二、自定義事件的處理流程是什麼?
要搞清楚,爲什麼點擊 歡迎 按鈕派發 welcome
事件之後,就會自動調用 sayHi
方法的原因。我們就必須分析 emit
函數的內部處理邏輯,該函數被定義在 runtime-core/src/componentEmits.t
文件中:
// packages/runtime-core/src/componentEmits.ts
export function emit(
instance: ComponentInternalInstance,
event: string,
...rawArgs: any[]
) {
const props = instance.vnode.props || EMPTY_OBJ
// 省略大部分代碼
let args = rawArgs
// convert handler name to camelCase. See issue #2249
let handlerName = toHandlerKey(camelize(event))
let handler = props[handlerName]
if (handler) {
callWithAsyncErrorHandling(
handler,
instance,
ErrorCodes.COMPONENT_EVENT_HANDLER,
args
)
}
}
其實在 emit
函數內部還會涉及 v-model update:xxx
事件的處理,關於 v-model
指令的內部原理,阿寶哥會寫單獨的文章來介紹。這裏我們只分析與當前示例相關的處理邏輯。
在 emit
函數中,會使用 toHandlerKey
函數把事件名轉換爲駝峯式的 handlerName
:
// packages/shared/src/index.ts
export const toHandlerKey = cacheStringFunction(
(str: string) => (str ? `on${capitalize(str)}` : ``)
)
在獲取 handlerName
之後,就會從 props
對象上獲取該 handlerName
對應的 handler
對象。如果該 handler
對象存在,則會調用 callWithAsyncErrorHandling
函數,來執行當前自定義事件對應的事件處理函數。callWithAsyncErrorHandling
函數的定義如下:
// packages/runtime-core/src/errorHandling.ts
export function callWithAsyncErrorHandling(
fn: Function | Function[],
instance: ComponentInternalInstance | null,
type: ErrorTypes,
args?: unknown[]
): any[] {
if (isFunction(fn)) {
const res = callWithErrorHandling(fn, instance, type, args)
if (res && isPromise(res)) {
res.catch(err => {
handleError(err, instance, type)
})
}
return res
}
// 處理多個事件處理器
const values = []
for (let i = 0; i < fn.length; i++) {
values.push(callWithAsyncErrorHandling(fn[i], instance, type, args))
}
return values
}
通過以上代碼可知,如果 fn
參數是函數對象的話,在 callWithAsyncErrorHandling
函數內部還會繼續調用 callWithErrorHandling
函數來最終執行事件處理函數:
// packages/runtime-core/src/errorHandling.ts
export function callWithErrorHandling(
fn: Function,
instance: ComponentInternalInstance | null,
type: ErrorTypes,
args?: unknown[]
) {
let res
try {
res = args ? fn(...args) : fn()
} catch (err) {
handleError(err, instance, type)
}
return res
}
在 callWithErrorHandling
函數內部,使用 try catch
語句來捕獲異常並進行異常處理。如果調用 fn
事件處理函數之後,返回的是一個 Promise
對象的話,則會通過 Promise
對象上的 catch
方法來處理異常。瞭解完上面的內容,再回顧一下前面見過的函數調用棧,相信此時你就不會再陌生了。
現在前面提到的 2 個問題,我們都已經找到答案了。爲了能更好地掌握自定義事件的相關內容,阿寶哥將使用 Vue 3 Template Explorer 這個在線工具,來分析一下示例中模板編譯的結果:
App 組件模板
<welcome-button v-on:welcome="sayHi"></welcome-button>
const _Vue = Vue
return function render(_ctx, _cache, $props, $setup, $data, $options) {
with (_ctx) {
const { resolveComponent: _resolveComponent, createVNode: _createVNode,
openBlock: _openBlock, createBlock: _createBlock } = _Vue
const _component_welcome_button = _resolveComponent("welcome-button")
return (_openBlock(), _createBlock(_component_welcome_button,
{ onWelcome: sayHi }, null, 8 /* PROPS */, ["onWelcome"]))
}
}
welcome-button 組件模板
<button v-on:click="$emit('welcome')">歡迎</button>
const _Vue = Vue
return function render(_ctx, _cache, $props, $setup, $data, $options) {
with (_ctx) {
const { createVNode: _createVNode, openBlock: _openBlock,
createBlock: _createBlock } = _Vue
return (_openBlock(), _createBlock("button", {
onClick: $event => ($emit('welcome'))
}, "歡迎", 8 /* PROPS */, ["onClick"]))
}
}
觀察以上結果,我們可知通過 v-on:
綁定的事件,都會轉換爲以 on
開頭的屬性,比如 onWelcome
和 onClick
。爲什麼要轉換成這種形式呢?這是因爲在 emit
函數內部會通過 toHandlerKey
和 camelize
這兩個函數對事件名進行轉換:
// packages/runtime-core/src/componentEmits.ts
export function emit(
instance: ComponentInternalInstance,
event: string,
...rawArgs: any[]
) {
// 省略大部分代碼
// convert handler name to camelCase. See issue #2249
let handlerName = toHandlerKey(camelize(event))
let handler = props[handlerName]
}
爲了搞清楚轉換規則,我們先來看一下 camelize
函數:
// packages/shared/src/index.ts
const camelizeRE = /-(\w)/g
export const camelize = cacheStringFunction(
(str: string): string => {
return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
}
)
觀察以上代碼,我們可以知道 camelize
函數的作用,用於把 kebab-case (短橫線分隔命名) 命名的事件名轉換爲 camelCase (駝峯命名法) 的事件名,比如 "test-event"
事件名經過 camelize
函數處理後,將被轉換爲 "testEvent"
。該轉換後的結果,還會通過 toHandlerKey
函數進行進一步處理,toHandlerKey
函數被定義在 shared/src/index.ts
文件中:
// packages/shared/src/index.ts
export const toHandlerKey = cacheStringFunction(
(str: string) => (str ? `on${capitalize(str)}` : ``)
)
export const capitalize = cacheStringFunction(
(str: string) => str.charAt(0).toUpperCase() + str.slice(1)
)
對於前面使用的 "testEvent"
事件名經過 toHandlerKey
函數處理後,將被最終轉換爲 "onTestEvent"
的形式。爲了能夠更直觀地瞭解事件監聽器的合法形式,我們來看一下 runtime-core
模塊中的測試用例:
// packages/runtime-core/__tests__/componentEmits.spec.ts
test('isEmitListener', () => {
const options = {
click: null,
'test-event': null,
fooBar: null,
FooBaz: null
}
expect(isEmitListener(options, 'onClick')).toBe(true)
expect(isEmitListener(options, 'onclick')).toBe(false)
expect(isEmitListener(options, 'onBlick')).toBe(false)
// .once listeners
expect(isEmitListener(options, 'onClickOnce')).toBe(true)
expect(isEmitListener(options, 'onclickOnce')).toBe(false)
// kebab-case option
expect(isEmitListener(options, 'onTestEvent')).toBe(true)
// camelCase option
expect(isEmitListener(options, 'onFooBar')).toBe(true)
// PascalCase option
expect(isEmitListener(options, 'onFooBaz')).toBe(true)
})
瞭解完事件監聽器的合法形式之後,我們再來看一下 cacheStringFunction
函數:
// packages/shared/src/index.ts
const cacheStringFunction = <T extends (str: string) => string>(fn: T): T => {
const cache: Record<string, string> = Object.create(null)
return ((str: string) => {
const hit = cache[str]
return hit || (cache[str] = fn(str))
}) as any
}
以上代碼也比較簡單,cacheStringFunction
函數的作用是爲了實現緩存功能。
三、阿寶哥有話說
3.1 如何在渲染函數中綁定事件?
在前面的示例中,我們通過 v-on
指令完成事件綁定,那麼在渲染函數中如何綁定事件呢?
<div id="app"></div>
<script>
const { createApp, defineComponent, h } = Vue
const Foo = defineComponent({
emits: ["foo"],
render() { return h("h3", "Vue 3 自定義事件")},
created() {
this.$emit('foo');
}
});
const onFoo = () => {
console.log("foo be called")
};
const Comp = () => h(Foo, { onFoo })
const app = createApp(Comp);
app.mount("#app")
</script>
在以上示例中,我們通過 defineComponent
全局 API 定義了 Foo
組件,然後通過 h
函數創建了函數式組件 Comp
,在創建 Comp
組件時,通過設置 onFoo
屬性實現了自定義事件的綁定操作。
3.2 如何只執行一次事件處理器?
在模板中設置
<welcome-button v-on:welcome.once="sayHi"></welcome-button>
const _Vue = Vue
return function render(_ctx, _cache, $props, $setup, $data, $options) {
with (_ctx) {
const { resolveComponent: _resolveComponent, createVNode: _createVNode,
openBlock: _openBlock, createBlock: _createBlock } = _Vue
const _component_welcome_button = _resolveComponent("welcome-button")
return (_openBlock(), _createBlock(_component_welcome_button,
{ onWelcomeOnce: sayHi }, null, 8 /* PROPS */, ["onWelcomeOnce"]))
}
}
在以上代碼中,我們使用了 once
事件修飾符,來實現只執行一次事件處理器的功能。除了 once
修飾符之外,還有其他的修飾符,比如:
<!-- 阻止單擊事件繼續傳播 -->
<a @click.stop="doThis"></a>
<!-- 提交事件不再重載頁面 -->
<form @submit.prevent="onSubmit"></form>
<!-- 修飾符可以串聯 -->
<a @click.stop.prevent="doThat"></a>
<!-- 只有修飾符 -->
<form @submit.prevent></form>
<!-- 添加事件監聽器時使用事件捕獲模式 -->
<!-- 即內部元素觸發的事件先在此處理,然後才交由內部元素進行處理 -->
<div @click.capture="doThis">...</div>
<!-- 只當在 event.target 是當前元素自身時觸發處理函數 -->
<!-- 即事件不是從內部元素觸發的 -->
<div @click.self="doThat">...</div>
在渲染函數中設置
<div id="app"></div>
<script>
const { createApp, defineComponent, h } = Vue
const Foo = defineComponent({
emits: ["foo"],
render() { return h("h3", "Vue 3 自定義事件")},
created() {
this.$emit('foo');
this.$emit('foo');
}
});
const onFoo = () => {
console.log("foo be called")
};
// 在事件名後添加Once,表示該事件處理器只執行一次
const Comp = () => h(Foo, { onFooOnce: onFoo })
const app = createApp(Comp);
app.mount("#app")
</script>
以上兩種方式都能生效的原因是,模板中的指令 v-on:welcome.once
,經過編譯後會轉換爲onWelcomeOnce
,並且在 emit
函數中定義了 once
修飾符的處理規則:
// packages/runtime-core/src/componentEmits.ts
export function emit(
instance: ComponentInternalInstance,
event: string,
...rawArgs: any[]
) {
const props = instance.vnode.props || EMPTY_OBJ
const onceHandler = props[handlerName + `Once`]
if (onceHandler) {
if (!instance.emitted) {
;(instance.emitted = {} as Record<string, boolean>)[handlerName] = true
} else if (instance.emitted[handlerName]) {
return
}
callWithAsyncErrorHandling(
onceHandler,
instance,
ErrorCodes.COMPONENT_EVENT_HANDLER,
args
)
}
}
3.3 如何添加多個事件處理器
在模板中設置
<div @click="foo(), bar()"/>
const _Vue = Vue
return function render(_ctx, _cache, $props, $setup, $data, $options) {
with (_ctx) {
const { createVNode: _createVNode, openBlock: _openBlock,
createBlock: _createBlock } = _Vue
return (_openBlock(), _createBlock("div", {
onClick: $event => (foo(), bar())
}, null, 8 /* PROPS */, ["onClick"]))
}
}
在渲染函數中設置
<div id="app"></div>
<script>
const { createApp, defineComponent, h } = Vue
const Foo = defineComponent({
emits: ["foo"],
render() { return h("h3", "Vue 3 自定義事件")},
created() {
this.$emit('foo');
}
});
const onFoo = () => {
console.log("foo be called")
};
const onBar = () => {
console.log("bar be called")
};
const Comp = () => h(Foo, { onFoo: [onFoo, onBar] })
const app = createApp(Comp);
app.mount("#app")
</script>
以上方式能夠生效的原因是,在前面介紹的 callWithAsyncErrorHandling
函數中含有多個事件處理器的處理邏輯:
// packages/runtime-core/src/errorHandling.ts
export function callWithAsyncErrorHandling(
fn: Function | Function[],
instance: ComponentInternalInstance | null,
type: ErrorTypes,
args?: unknown[]
): any[] {
if (isFunction(fn)) {
// 省略部分代碼
}
const values = []
for (let i = 0; i < fn.length; i++) {
values.push(callWithAsyncErrorHandling(fn[i], instance, type, args))
}
return values
}
3.4 Vue 3 的 $emit
與 Vue 2 的 $emit
有什麼區別?
在 Vue 2 中 $emit
方法是 Vue.prototype
對象上的屬性,而 Vue 3 上的 $emit
是組件實例上的一個屬性,instance.emit = emit.bind(null, instance)
。
// src/core/instance/events.js
export function eventsMixin (Vue: Class<Component>) {
const hookRE = /^hook:/
// 省略$on、$once和$off等方法的定義
// Vue實例是一個EventBus對象
Vue.prototype.$emit = function (event: string): Component {
const vm: Component = this
let cbs = vm._events[event]
if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs
const args = toArray(arguments, 1)
const info = `event handler for "${event}"`
for (let i = 0, l = cbs.length; i < l; i++) {
invokeWithErrorHandling(cbs[i], vm, args, vm, info)
}
}
return vm
}
}
本文阿寶哥主要介紹了在 Vue 3 中自定義事件背後的祕密。爲了讓大家能夠更深入地掌握自定義事件的相關知識,阿寶哥從源碼的角度分析了 $emit
方法的來源和自定義事件的處理流程。
在 Vue 3.0 進階系列第一篇文章 Vue 3.0 進階之指令探祕 中,我們已經介紹了指令相關的知識,有了這些基礎,之後阿寶哥將帶大家一起探索 Vue 3 雙向綁定的原理,感興趣的小夥伴不要錯過喲。
四、參考資源
-
Vue 3 官網 - 事件處理 -
Vue 3 官網 - 自定義事件 -
Vue 3 官網 - 全局 API
本文分享自微信公衆號 - 前端自習課(FE-study)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。