自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Vue 3.0 進(jìn)階之自定義事件探秘

開發(fā) 項(xiàng)目管理
這是 Vue 3.0 進(jìn)階系列 的第二篇文章,該系列的第一篇文章是 Vue 3.0 進(jìn)階之指令探秘。本文阿寶哥將以一個簡單的示例為切入點(diǎn),帶大家一起一步步揭開自定義事件背后的秘密。

 

[[382053]]

這是 Vue 3.0 進(jìn)階系列 的第二篇文章,該系列的第一篇文章是 Vue 3.0 進(jìn)階之指令探秘。本文阿寶哥將以一個簡單的示例為切入點(diǎn),帶大家一起一步步揭開自定義事件背后的秘密。

  1. <div id="app"></div> 
  2. <script> 
  3.    const app = Vue.createApp({ 
  4.      template: '<welcome-button v-on:welcome="sayHi"></welcome-button>'
  5.      methods: { 
  6.        sayHi() { 
  7.          console.log('你好,我是阿寶哥!'); 
  8.        } 
  9.      } 
  10.     }) 
  11.  
  12.    app.component('welcome-button', { 
  13.      emits: ['welcome'], 
  14.      template: ` 
  15.        <button v-on:click="$emit('welcome')"
  16.           歡迎 
  17.        </button> 
  18.       ` 
  19.     }) 
  20.     app.mount("#app"
  21. </script> 

在以上示例中,我們先通過 Vue.createApp 方法創(chuàng)建 app 對象,之后利用該對象上的 component 方法注冊全局組件 —— welcome-button 組件。在定義該組件時(shí),我們通過 emits 屬性定義了該組件上的自定義事件。當(dāng)然用戶點(diǎn)擊 歡迎 按鈕時(shí),就會發(fā)出 welcome 事件,之后就會調(diào)用 sayHi 方法,接著控制臺就會輸出 你好,我是阿寶哥! 。

雖然該示例比較簡單,但也存在以下 2 個問題:

  • $emit 方法來自哪里?
  • 自定義事件的處理流程是什么?

下面我們將圍繞這些問題來進(jìn)一步分析自定義事件背后的機(jī)制,首先我們先來分析第一個問題。

一、$emit 方法來自哪里?

使用 Chrome 開發(fā)者工具,我們在 sayHi 方法內(nèi)部加個斷點(diǎn),然后點(diǎn)擊 歡迎 按鈕,此時(shí)函數(shù)調(diào)用棧如下圖所示:


在上圖右側(cè)的調(diào)用棧,我們發(fā)現(xiàn)了一個存在于 componentEmits.ts 文件中的 emit 方法。但在模板中,我們使用的是 $emit 方法,為了搞清楚這個問題,我們來看一下 onClick 方法:


由上圖可知,我們的 $emit 方法來自 _ctx 對象,那么該對象是什么對象呢?同樣,利用斷點(diǎn)我們可以看到 _ctx 對象的內(nèi)部結(jié)構(gòu):


很明顯 _ctx 對象是一個 Proxy 對象,如果你對 Proxy 對象還不了解,可以閱讀 你不知道的 Proxy 這篇文章。當(dāng)訪問 _ctx 對象的 $emit 屬性時(shí),將會進(jìn)入 get 捕獲器,所以接下來我們來分析 get 捕獲器:


通過 [[FunctionLocation]] 屬性,我們找到了 get 捕獲器的定義,具體如下所示:

  1. // packages/runtime-core/src/componentPublicInstance.ts 
  2. export const RuntimeCompiledPublicInstanceProxyHandlers = extend( 
  3.   {}, 
  4.   PublicInstanceProxyHandlers, 
  5.   { 
  6.     get(target: ComponentRenderContext, key: string) { 
  7.       // fast path for unscopables when using `with` block 
  8.       if ((key as any) === Symbol.unscopables) { 
  9.         return 
  10.       } 
  11.       return PublicInstanceProxyHandlers.get!(target, key, target) 
  12.     }, 
  13.     has(_: ComponentRenderContext, key: string) { 
  14.       const has = key[0] !== '_' && !isGloballyWhitelisted(key
  15.       // 省略部分代碼 
  16.       return has 
  17.     } 
  18.   } 

觀察以上代碼可知,在 get 捕獲器內(nèi)部會繼續(xù)調(diào)用 PublicInstanceProxyHandlers 對象的 get 方法來獲取 key 對應(yīng)的值。由于 PublicInstanceProxyHandlers 內(nèi)部的代碼相對比較復(fù)雜,這里我們只分析與示例相關(guān)的代碼:

  1. // packages/runtime-core/src/componentPublicInstance.ts 
  2. export const PublicInstanceProxyHandlers: ProxyHandler<any> = { 
  3.   get({ _: instance }: ComponentRenderContext, key: string) { 
  4.     const { ctx, setupState, data, props, accessCache, type, appContext } = instance 
  5.     
  6.     // 省略大部分內(nèi)容 
  7.     const publicGetter = publicPropertiesMap[key
  8.     // public $xxx properties 
  9.     if (publicGetter) { 
  10.       if (key === '$attrs') { 
  11.         track(instance, TrackOpTypes.GET, key
  12.         __DEV__ && markAttrsAccessed() 
  13.       } 
  14.       return publicGetter(instance) 
  15.     }, 
  16.     // 省略set和has捕獲器 

在上面代碼中,我們看到了 publicPropertiesMap 對象,該對象被定義在 componentPublicInstance.ts 文件中:

  1. // packages/runtime-core/src/componentPublicInstance.ts 
  2. const publicPropertiesMap: PublicPropertiesMap = extend(Object.create(null), { 
  3.   $: i => i, 
  4.   $el: i => i.vnode.el, 
  5.   $data: i => i.data, 
  6.   $props: i => (__DEV__ ? shallowReadonly(i.props) : i.props), 
  7.   $attrs: i => (__DEV__ ? shallowReadonly(i.attrs) : i.attrs), 
  8.   $slots: i => (__DEV__ ? shallowReadonly(i.slots) : i.slots), 
  9.   $refs: i => (__DEV__ ? shallowReadonly(i.refs) : i.refs), 
  10.   $parent: i => getPublicInstance(i.parent), 
  11.   $root: i => getPublicInstance(i.root), 
  12.   $emit: i => i.emit, 
  13.   $options: i => (__FEATURE_OPTIONS_API__ ? resolveMergedOptions(i) : i.type), 
  14.   $forceUpdate: i => () => queueJob(i.update), 
  15.   $nextTick: i => nextTick.bind(i.proxy!), 
  16.   $watch: i => (__FEATURE_OPTIONS_API__ ? instanceWatch.bind(i) : NOOP) 
  17. as PublicPropertiesMap) 

在 publicPropertiesMap 對象中,我們找到了 $emit 屬性,該屬性的值為 $emit: i => i.emit,即 $emit 指向的是參數(shù) i 對象的 emit 屬性。下面我們來看一下,當(dāng)獲取 $emit 屬性時(shí),target 對象是什么:


由上圖可知 target 對象有一個 _ 屬性,該屬性的值是一個對象,且該對象含有 vnode、type 和 parent 等屬性。因此我們猜測 _ 屬性的值是組件實(shí)例。為了證實(shí)這個猜測,利用 Chrome 開發(fā)者工具,我們就可以輕易地分析出組件掛載過程中調(diào)用了哪些函數(shù):


在上圖中,我們看到了在組件掛載階段,調(diào)用了 createComponentInstance 函數(shù)。顧名思義,該函數(shù)用于創(chuàng)建組件實(shí)例,其具體實(shí)現(xiàn)如下所示:

  1. // packages/runtime-core/src/component.ts 
  2. export function createComponentInstance( 
  3.   vnode: VNode, 
  4.   parent: ComponentInternalInstance | null
  5.   suspense: SuspenseBoundary | null 
  6. ) { 
  7.   const type = vnode.type as ConcreteComponent 
  8.   const appContext = 
  9.     (parent ? parent.appContext : vnode.appContext) || emptyAppContext 
  10.  
  11.   const instance: ComponentInternalInstance = { 
  12.     uid: uid++, 
  13.     vnode, 
  14.     type, 
  15.     parent, 
  16.     appContext, 
  17.     // 省略大部分屬性 
  18.     emit: null as any,  
  19.     emitted: null
  20.   } 
  21.   if (__DEV__) { // 開發(fā)模式 
  22.     instance.ctx = createRenderContext(instance) 
  23.   } else { // 生產(chǎn)模式 
  24.     instance.ctx = { _: instance } 
  25.   } 
  26.   instance.root = parent ? parent.root : instance 
  27.   instance.emit = emit.bind(null, instance) 
  28.  
  29.   return instance 

在以上代碼中,我們除了發(fā)現(xiàn) instance 對象之外,還看到了 instance.emit = emit.bind(null, instance) 這個語句。這時(shí)我們就找到了 $emit 方法來自哪里的答案。弄清楚第一個問題之后,接下來我們來分析自定義事件的處理流程。

二、自定義事件的處理流程是什么?

要搞清楚,為什么點(diǎn)擊 歡迎 按鈕派發(fā) welcome 事件之后,就會自動調(diào)用 sayHi 方法的原因。我們就必須分析 emit 函數(shù)的內(nèi)部處理邏輯,該函數(shù)被定義在 runtime-core/src/componentEmits.t 文件中:

  1. // packages/runtime-core/src/componentEmits.ts 
  2. export function emit( 
  3.   instance: ComponentInternalInstance, 
  4.   event: string, 
  5.   ...rawArgs: any[] 
  6. ) { 
  7.   const props = instance.vnode.props || EMPTY_OBJ 
  8.  // 省略大部分代碼 
  9.   let args = rawArgs 
  10.  
  11.   // convert handler name to camelCase. See issue #2249 
  12.   let handlerName = toHandlerKey(camelize(event)) 
  13.   let handler = props[handlerName] 
  14.  
  15.   if (handler) { 
  16.     callWithAsyncErrorHandling( 
  17.       handler, 
  18.       instance, 
  19.       ErrorCodes.COMPONENT_EVENT_HANDLER, 
  20.       args 
  21.     ) 
  22.   } 

其實(shí)在 emit 函數(shù)內(nèi)部還會涉及 v-model update:xxx 事件的處理,關(guān)于 v-model 指令的內(nèi)部原理,阿寶哥會寫單獨(dú)的文章來介紹。這里我們只分析與當(dāng)前示例相關(guān)的處理邏輯。

在 emit 函數(shù)中,會使用 toHandlerKey 函數(shù)把事件名轉(zhuǎn)換為駝峰式的 handlerName:

  1. // packages/shared/src/index.ts 
  2. export const toHandlerKey = cacheStringFunction( 
  3.   (str: string) => (str ? `on${capitalize(str)}` : ``) 

在獲取 handlerName 之后,就會從 props 對象上獲取該 handlerName 對應(yīng)的 handler對象。如果該 handler 對象存在,則會調(diào)用 callWithAsyncErrorHandling 函數(shù),來執(zhí)行當(dāng)前自定義事件對應(yīng)的事件處理函數(shù)。callWithAsyncErrorHandling 函數(shù)的定義如下:

  1. // packages/runtime-core/src/errorHandling.ts 
  2. export function callWithAsyncErrorHandling( 
  3.   fn: Function | Function[], 
  4.   instance: ComponentInternalInstance | null
  5.   type: ErrorTypes, 
  6.   args?: unknown[] 
  7. ): any[] { 
  8.   if (isFunction(fn)) { 
  9.     const res = callWithErrorHandling(fn, instance, type, args) 
  10.     if (res && isPromise(res)) { 
  11.       res.catch(err => { 
  12.         handleError(err, instance, type) 
  13.       }) 
  14.     } 
  15.     return res 
  16.   } 
  17.  
  18.   // 處理多個事件處理器 
  19.   const values = [] 
  20.   for (let i = 0; i < fn.length; i++) { 
  21.     values.push(callWithAsyncErrorHandling(fn[i], instance, type, args)) 
  22.   } 
  23.   return values 

通過以上代碼可知,如果 fn 參數(shù)是函數(shù)對象的話,在 callWithAsyncErrorHandling 函數(shù)內(nèi)部還會繼續(xù)調(diào)用 callWithErrorHandling 函數(shù)來最終執(zhí)行事件處理函數(shù):

  1. // packages/runtime-core/src/errorHandling.ts 
  2. export function callWithErrorHandling( 
  3.   fn: Function
  4.   instance: ComponentInternalInstance | null
  5.   type: ErrorTypes, 
  6.   args?: unknown[] 
  7. ) { 
  8.   let res 
  9.   try { 
  10.     res = args ? fn(...args) : fn() 
  11.   } catch (err) { 
  12.     handleError(err, instance, type) 
  13.   } 
  14.   return res 

在 callWithErrorHandling 函數(shù)內(nèi)部,使用 try catch 語句來捕獲異常并進(jìn)行異常處理。如果調(diào)用 fn 事件處理函數(shù)之后,返回的是一個 Promise 對象的話,則會通過 Promise 對象上的 catch 方法來處理異常。了解完上面的內(nèi)容,再回顧一下前面見過的函數(shù)調(diào)用棧,相信此時(shí)你就不會再陌生了。


現(xiàn)在前面提到的 2 個問題,我們都已經(jīng)找到答案了。為了能更好地掌握自定義事件的相關(guān)內(nèi)容,阿寶哥將使用 Vue 3 Template Explorer 這個在線工具,來分析一下示例中模板編譯的結(jié)果:

App 組件模板

  1. <welcome-button v-on:welcome="sayHi"></welcome-button> 
  2.  
  3. const _Vue = Vue 
  4. return function render(_ctx, _cache, $props, $setup, $data, $options) { 
  5.   with (_ctx) { 
  6.     const { resolveComponent: _resolveComponent, createVNode: _createVNode,  
  7.       openBlock: _openBlock, createBlock: _createBlock } = _Vue 
  8.     const _component_welcome_button = _resolveComponent("welcome-button"
  9.  
  10.     return (_openBlock(), _createBlock(_component_welcome_button, 
  11.      { onWelcome: sayHi }, null, 8 /* PROPS */, ["onWelcome"])) 
  12.   } 

welcome-button 組件模板

  1. <button v-on:click="$emit('welcome')">歡迎</button> 
  2.  
  3. const _Vue = Vue 
  4. return function render(_ctx, _cache, $props, $setup, $data, $options) { 
  5.   with (_ctx) { 
  6.     const { createVNode: _createVNode, openBlock: _openBlock, 
  7.       createBlock: _createBlock } = _Vue 
  8.  
  9.     return (_openBlock(), _createBlock("button", { 
  10.       onClick: $event => ($emit('welcome')) 
  11.     }, "歡迎", 8 /* PROPS */, ["onClick"])) 
  12.   } 

觀察以上結(jié)果,我們可知通過 v-on: 綁定的事件,都會轉(zhuǎn)換為以 on 開頭的屬性,比如 onWelcome 和 onClick。為什么要轉(zhuǎn)換成這種形式呢?這是因?yàn)樵?emit 函數(shù)內(nèi)部會通過 toHandlerKey 和 camelize 這兩個函數(shù)對事件名進(jìn)行轉(zhuǎn)換:

  1. // packages/runtime-core/src/componentEmits.ts 
  2. export function emit( 
  3.   instance: ComponentInternalInstance, 
  4.   event: string, 
  5.   ...rawArgs: any[] 
  6. ) { 
  7.  // 省略大部分代碼 
  8.   // convert handler name to camelCase. See issue #2249 
  9.   let handlerName = toHandlerKey(camelize(event)) 
  10.   let handler = props[handlerName] 

為了搞清楚轉(zhuǎn)換規(guī)則,我們先來看一下 camelize 函數(shù):

  1. // packages/shared/src/index.ts 
  2. const camelizeRE = /-(\w)/g 
  3.  
  4. export const camelize = cacheStringFunction( 
  5.   (str: string): string => { 
  6.     return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : '')) 
  7.   } 

觀察以上代碼,我們可以知道 camelize 函數(shù)的作用,用于把 kebab-case (短橫線分隔命名) 命名的事件名轉(zhuǎn)換為 camelCase (駝峰命名法) 的事件名,比如 "test-event" 事件名經(jīng)過 camelize 函數(shù)處理后,將被轉(zhuǎn)換為 "testEvent"。該轉(zhuǎn)換后的結(jié)果,還會通過 toHandlerKey 函數(shù)進(jìn)行進(jìn)一步處理,toHandlerKey 函數(shù)被定義在 shared/src/index.ts文件中:

  1. // packages/shared/src/index.ts 
  2. export const toHandlerKey = cacheStringFunction( 
  3.   (str: string) => (str ? `on${capitalize(str)}` : ``) 
  4.  
  5. export const capitalize = cacheStringFunction( 
  6.   (str: string) => str.charAt(0).toUpperCase() + str.slice(1) 

對于前面使用的 "testEvent" 事件名經(jīng)過 toHandlerKey 函數(shù)處理后,將被最終轉(zhuǎn)換為 "onTestEvent" 的形式。為了能夠更直觀地了解事件監(jiān)聽器的合法形式,我們來看一下 runtime-core 模塊中的測試用例:

  1. // packages/runtime-core/__tests__/componentEmits.spec.ts 
  2. test('isEmitListener', () => { 
  3.   const options = { 
  4.     click: null
  5.     'test-event'null
  6.     fooBar: null
  7.     FooBaz: null 
  8.   } 
  9.   expect(isEmitListener(options, 'onClick')).toBe(true
  10.   expect(isEmitListener(options, 'onclick')).toBe(false
  11.   expect(isEmitListener(options, 'onBlick')).toBe(false
  12.   // .once listeners 
  13.   expect(isEmitListener(options, 'onClickOnce')).toBe(true
  14.   expect(isEmitListener(options, 'onclickOnce')).toBe(false
  15.   // kebab-case option 
  16.   expect(isEmitListener(options, 'onTestEvent')).toBe(true
  17.   // camelCase option 
  18.   expect(isEmitListener(options, 'onFooBar')).toBe(true
  19.   // PascalCase option 
  20.   expect(isEmitListener(options, 'onFooBaz')).toBe(true
  21. }) 

了解完事件監(jiān)聽器的合法形式之后,我們再來看一下 cacheStringFunction 函數(shù):

  1. // packages/shared/src/index.ts 
  2. const cacheStringFunction = <T extends (str: string) => string>(fn: T): T => { 
  3.   const cache: Record<string, string> = Object.create(null
  4.   return ((str: string) => { 
  5.     const hit = cache[str] 
  6.     return hit || (cache[str] = fn(str)) 
  7.   }) as any 

以上代碼也比較簡單,cacheStringFunction 函數(shù)的作用是為了實(shí)現(xiàn)緩存功能。

三、阿寶哥有話說

3.1 如何在渲染函數(shù)中綁定事件?

在前面的示例中,我們通過 v-on 指令完成事件綁定,那么在渲染函數(shù)中如何綁定事件呢?

  1. <div id="app"></div> 
  2. <script> 
  3.   const { createApp, defineComponent, h } = Vue 
  4.    
  5.   const Foo = defineComponent({ 
  6.     emits: ["foo"],  
  7.     render() { return h("h3""Vue 3 自定義事件")}, 
  8.     created() { 
  9.       this.$emit('foo'); 
  10.     } 
  11.   }); 
  12.   const onFoo = () => { 
  13.     console.log("foo be called"
  14.   }; 
  15.   const Comp = () => h(Foo, { onFoo }) 
  16.   const app = createApp(Comp); 
  17.   app.mount("#app"
  18. </script> 

在以上示例中,我們通過 defineComponent 全局 API 定義了 Foo 組件,然后通過 h 函數(shù)創(chuàng)建了函數(shù)式組件 Comp,在創(chuàng)建 Comp 組件時(shí),通過設(shè)置 onFoo 屬性實(shí)現(xiàn)了自定義事件的綁定操作。

3.2 如何只執(zhí)行一次事件處理器?

在模板中設(shè)置

  1. <welcome-button v-on:welcome.once="sayHi"></welcome-button> 
  2.  
  3. const _Vue = Vue 
  4. return function render(_ctx, _cache, $props, $setup, $data, $options) { 
  5.   with (_ctx) { 
  6.     const { resolveComponent: _resolveComponent, createVNode: _createVNode,  
  7.       openBlock: _openBlock, createBlock: _createBlock } = _Vue 
  8.     const _component_welcome_button = _resolveComponent("welcome-button"
  9.  
  10.     return (_openBlock(), _createBlock(_component_welcome_button,  
  11.       { onWelcomeOnce: sayHi }, null, 8 /* PROPS */, ["onWelcomeOnce"])) 
  12.   } 

在以上代碼中,我們使用了 once 事件修飾符,來實(shí)現(xiàn)只執(zhí)行一次事件處理器的功能。除了 once 修飾符之外,還有其他的修飾符,比如:

  1. <!-- 阻止單擊事件繼續(xù)傳播 --> 
  2. <a @click.stop="doThis"></a> 
  3.  
  4. <!-- 提交事件不再重載頁面 --> 
  5. <form @submit.prevent="onSubmit"></form> 
  6.  
  7. <!-- 修飾符可以串聯(lián) --> 
  8. <a @click.stop.prevent="doThat"></a> 
  9.  
  10. <!-- 只有修飾符 --> 
  11. <form @submit.prevent></form> 
  12.  
  13. <!-- 添加事件監(jiān)聽器時(shí)使用事件捕獲模式 --> 
  14. <!-- 即內(nèi)部元素觸發(fā)的事件先在此處理,然后才交由內(nèi)部元素進(jìn)行處理 --> 
  15. <div @click.capture="doThis">...</div> 
  16.  
  17. <!-- 只當(dāng)在 event.target 是當(dāng)前元素自身時(shí)觸發(fā)處理函數(shù) --> 
  18. <!-- 即事件不是從內(nèi)部元素觸發(fā)的 --> 
  19. <div @click.self="doThat">...</div> 

 在渲染函數(shù)中設(shè)置

  1. <div id="app"></div> 
  2. <script> 
  3.    const { createApp, defineComponent, h } = Vue 
  4.    const Foo = defineComponent({ 
  5.      emits: ["foo"],  
  6.      render() { return h("h3""Vue 3 自定義事件")}, 
  7.      created() { 
  8.        this.$emit('foo'); 
  9.        this.$emit('foo'); 
  10.      } 
  11.    }); 
  12.    const onFoo = () => { 
  13.      console.log("foo be called"
  14.    }; 
  15.    // 在事件名后添加Once,表示該事件處理器只執(zhí)行一次 
  16.    const Comp = () => h(Foo, { onFooOnce: onFoo }) 
  17.    const app = createApp(Comp); 
  18.    app.mount("#app"
  19. </script> 

以上兩種方式都能生效的原因是,模板中的指令 v-on:welcome.once,經(jīng)過編譯后會轉(zhuǎn)換為onWelcomeOnce,并且在 emit 函數(shù)中定義了 once 修飾符的處理規(guī)則:

  1. // packages/runtime-core/src/componentEmits.ts 
  2. export function emit( 
  3.   instance: ComponentInternalInstance, 
  4.   event: string, 
  5.   ...rawArgs: any[] 
  6. ) { 
  7.   const props = instance.vnode.props || EMPTY_OBJ 
  8.  
  9.   const onceHandler = props[handlerName + `Once`] 
  10.   if (onceHandler) { 
  11.     if (!instance.emitted) { 
  12.       ;(instance.emitted = {} as Record<string, boolean>)[handlerName] = true 
  13.     } else if (instance.emitted[handlerName]) { 
  14.       return 
  15.     } 
  16.     callWithAsyncErrorHandling( 
  17.       onceHandler, 
  18.       instance, 
  19.       ErrorCodes.COMPONENT_EVENT_HANDLER, 
  20.       args 
  21.     ) 
  22.   } 

3.3 如何添加多個事件處理器

在模板中設(shè)置

  1. <div @click="foo(), bar()"/> 
  2.    
  3. const _Vue = Vue 
  4. return function render(_ctx, _cache, $props, $setup, $data, $options) { 
  5.   with (_ctx) { 
  6.     const { createVNode: _createVNode, openBlock: _openBlock,  
  7.       createBlock: _createBlock } = _Vue 
  8.  
  9.     return (_openBlock(), _createBlock("div", { 
  10.       onClick: $event => (foo(), bar()) 
  11.     }, null, 8 /* PROPS */, ["onClick"])) 
  12.   } 

 在渲染函數(shù)中設(shè)置

  1. <div id="app"></div> 
  2. <script> 
  3.    const { createApp, defineComponent, h } = Vue 
  4.    const Foo = defineComponent({ 
  5.      emits: ["foo"],  
  6.      render() { return h("h3""Vue 3 自定義事件")}, 
  7.      created() { 
  8.        this.$emit('foo'); 
  9.      } 
  10.    }); 
  11.    const onFoo = () => { 
  12.      console.log("foo be called"
  13.    }; 
  14.    const onBar = () => { 
  15.      console.log("bar be called"
  16.    }; 
  17.    const Comp = () => h(Foo, { onFoo: [onFoo, onBar] }) 
  18.    const app = createApp(Comp); 
  19.   app.mount("#app"
  20. </script> 

以上方式能夠生效的原因是,在前面介紹的 callWithAsyncErrorHandling 函數(shù)中含有多個事件處理器的處理邏輯:

  1. // packages/runtime-core/src/errorHandling.ts 
  2. export function callWithAsyncErrorHandling( 
  3.   fn: Function | Function[], 
  4.   instance: ComponentInternalInstance | null
  5.   type: ErrorTypes, 
  6.   args?: unknown[] 
  7. ): any[] { 
  8.   if (isFunction(fn)) { 
  9.    // 省略部分代碼 
  10.   } 
  11.  
  12.   const values = [] 
  13.   for (let i = 0; i < fn.length; i++) { 
  14.     values.push(callWithAsyncErrorHandling(fn[i], instance, type, args)) 
  15.   } 
  16.   return values 

3.4 Vue 3 的 $emit 與 Vue 2 的 $emit 有什么區(qū)別?

在 Vue 2 中 $emit 方法是 Vue.prototype 對象上的屬性,而 Vue 3 上的 $emit 是組件實(shí)例上的一個屬性,instance.emit = emit.bind(null, instance)。

  1. // src/core/instance/events.js 
  2. export function eventsMixin (Vue: Class<Component>) { 
  3.   const hookRE = /^hook:/ 
  4.  
  5.   // 省略$on、$once和$off等方法的定義 
  6.   // Vue實(shí)例是一個EventBus對象 
  7.   Vue.prototype.$emit = function (event: string): Component { 
  8.     const vm: Component = this 
  9.     let cbs = vm._events[event] 
  10.     if (cbs) { 
  11.       cbs = cbs.length > 1 ? toArray(cbs) : cbs 
  12.       const args = toArray(arguments, 1) 
  13.       const info = `event handler for "${event}"
  14.       for (let i = 0, l = cbs.length; i < l; i++) { 
  15.         invokeWithErrorHandling(cbs[i], vm, args, vm, info) 
  16.       } 
  17.     } 
  18.     return vm 
  19.   } 

本文阿寶哥主要介紹了在 Vue 3 中自定義事件背后的秘密。為了讓大家能夠更深入地掌握自定義事件的相關(guān)知識,阿寶哥從源碼的角度分析了 $emit 方法的來源和自定義事件的處理流程。

在 Vue 3.0 進(jìn)階系列第一篇文章 Vue 3.0 進(jìn)階之指令探秘 中,我們已經(jīng)介紹了指令相關(guān)的知識,有了這些基礎(chǔ),之后阿寶哥將帶大家一起探索 Vue 3 雙向綁定的原理,感興趣的小伙伴不要錯過喲。

四、參考資源

  • Vue 3 官網(wǎng) - 事件處理
  • Vue 3 官網(wǎng) - 自定義事件
  • Vue 3 官網(wǎng) - 全局 API

 

責(zé)任編輯:姜華 來源: 全棧修仙之路
相關(guān)推薦

2021-02-16 16:41:45

Vue項(xiàng)目指令

2021-02-26 05:19:20

Vue 3.0 VNode虛擬

2021-02-28 20:41:18

Vue注入Angular

2021-02-19 23:07:02

Vue綁定組件

2021-02-22 21:49:33

Vue動態(tài)組件

2021-08-11 14:29:20

鴻蒙HarmonyOS應(yīng)用

2021-03-04 22:31:02

Vue進(jìn)階函數(shù)

2009-08-04 09:56:46

C#事件處理自定義事件

2009-09-03 15:46:57

C#自定義事件

2022-05-07 10:22:32

JavaScript自定義前端

2022-02-22 13:14:30

Vue自定義指令注冊

2020-04-15 15:35:29

vue.jsCSS開發(fā)

2010-08-12 09:45:33

jQuery自定義事件

2009-08-04 12:56:51

C#自定義事件

2021-03-09 22:29:46

Vue 響應(yīng)式API

2010-08-13 11:34:54

Flex自定義事件

2021-03-08 00:08:29

Vue應(yīng)用掛載

2009-08-04 13:53:58

C#委托類C#事件

2021-07-05 15:35:47

Vue前端代碼

2021-10-26 10:07:02

鴻蒙HarmonyOS應(yīng)用
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號