Vue 3.0 进阶之自定义事件探秘

开发 项目管理
这是 Vue 3.0 进阶系列 的第二篇文章,该系列的第一篇文章是 Vue 3.0 进阶之指令探秘。本文阿宝哥将以一个简单的示例为切入点,带大家一起一步步揭开自定义事件背后的秘密。

 

[[382053]]

这是 Vue 3.0 进阶系列 的第二篇文章,该系列的第一篇文章是 Vue 3.0 进阶之指令探秘。本文阿宝哥将以一个简单的示例为切入点,带大家一起一步步揭开自定义事件背后的秘密。

  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 方法创建 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 捕获器的定义,具体如下所示:

  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 捕获器内部会继续调用 PublicInstanceProxyHandlers 对象的 get 方法来获取 key 对应的值。由于 PublicInstanceProxyHandlers 内部的代码相对比较复杂,这里我们只分析与示例相关的代码:

  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.     // 省略大部分内容 
  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 指向的是参数 i 对象的 emit 属性。下面我们来看一下,当获取 $emit 属性时,target 对象是什么:


由上图可知 target 对象有一个 _ 属性,该属性的值是一个对象,且该对象含有 vnode、type 和 parent 等属性。因此我们猜测 _ 属性的值是组件实例。为了证实这个猜测,利用 Chrome 开发者工具,我们就可以轻易地分析出组件挂载过程中调用了哪些函数:


在上图中,我们看到了在组件挂载阶段,调用了 createComponentInstance 函数。顾名思义,该函数用于创建组件实例,其具体实现如下所示:

  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__) { // 开发模式 
  22.     instance.ctx = createRenderContext(instance) 
  23.   } else { // 生产模式 
  24.     instance.ctx = { _: instance } 
  25.   } 
  26.   instance.root = parent ? parent.root : instance 
  27.   instance.emit = emit.bind(null, instance) 
  28.  
  29.   return instance 

在以上代码中,我们除了发现 instance 对象之外,还看到了 instance.emit = emit.bind(null, instance) 这个语句。这时我们就找到了 $emit 方法来自哪里的答案。弄清楚第一个问题之后,接下来我们来分析自定义事件的处理流程。

二、自定义事件的处理流程是什么?

要搞清楚,为什么点击 欢迎 按钮派发 welcome 事件之后,就会自动调用 sayHi 方法的原因。我们就必须分析 emit 函数的内部处理逻辑,该函数被定义在 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.   } 

其实在 emit 函数内部还会涉及 v-model update:xxx 事件的处理,关于 v-model 指令的内部原理,阿宝哥会写单独的文章来介绍。这里我们只分析与当前示例相关的处理逻辑。

在 emit 函数中,会使用 toHandlerKey 函数把事件名转换为驼峰式的 handlerName:

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

在获取 handlerName 之后,就会从 props 对象上获取该 handlerName 对应的 handler对象。如果该 handler 对象存在,则会调用 callWithAsyncErrorHandling 函数,来执行当前自定义事件对应的事件处理函数。callWithAsyncErrorHandling 函数的定义如下:

  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 参数是函数对象的话,在 callWithAsyncErrorHandling 函数内部还会继续调用 callWithErrorHandling 函数来最终执行事件处理函数:

  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 函数内部,使用 try catch 语句来捕获异常并进行异常处理。如果调用 fn 事件处理函数之后,返回的是一个 Promise 对象的话,则会通过 Promise 对象上的 catch 方法来处理异常。了解完上面的内容,再回顾一下前面见过的函数调用栈,相信此时你就不会再陌生了。


现在前面提到的 2 个问题,我们都已经找到答案了。为了能更好地掌握自定义事件的相关内容,阿宝哥将使用 Vue 3 Template Explorer 这个在线工具,来分析一下示例中模板编译的结果:

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.   } 

观察以上结果,我们可知通过 v-on: 绑定的事件,都会转换为以 on 开头的属性,比如 onWelcome 和 onClick。为什么要转换成这种形式呢?这是因为在 emit 函数内部会通过 toHandlerKey 和 camelize 这两个函数对事件名进行转换:

  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] 

为了搞清楚转换规则,我们先来看一下 camelize 函数:

  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 函数的作用,用于把 kebab-case (短横线分隔命名) 命名的事件名转换为 camelCase (驼峰命名法) 的事件名,比如 "test-event" 事件名经过 camelize 函数处理后,将被转换为 "testEvent"。该转换后的结果,还会通过 toHandlerKey 函数进行进一步处理,toHandlerKey 函数被定义在 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" 事件名经过 toHandlerKey 函数处理后,将被最终转换为 "onTestEvent" 的形式。为了能够更直观地了解事件监听器的合法形式,我们来看一下 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. }) 

了解完事件监听器的合法形式之后,我们再来看一下 cacheStringFunction 函数:

  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 函数的作用是为了实现缓存功能。

三、阿宝哥有话说

3.1 如何在渲染函数中绑定事件?

在前面的示例中,我们通过 v-on 指令完成事件绑定,那么在渲染函数中如何绑定事件呢?

  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 函数创建了函数式组件 Comp,在创建 Comp 组件时,通过设置 onFoo 属性实现了自定义事件的绑定操作。

3.2 如何只执行一次事件处理器?

在模板中设置

  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 事件修饰符,来实现只执行一次事件处理器的功能。除了 once 修饰符之外,还有其他的修饰符,比如:

  1. <!-- 阻止单击事件继续传播 --> 
  2. <a @click.stop="doThis"></a> 
  3.  
  4. <!-- 提交事件不再重载页面 --> 
  5. <form @submit.prevent="onSubmit"></form> 
  6.  
  7. <!-- 修饰符可以串联 --> 
  8. <a @click.stop.prevent="doThat"></a> 
  9.  
  10. <!-- 只有修饰符 --> 
  11. <form @submit.prevent></form> 
  12.  
  13. <!-- 添加事件监听器时使用事件捕获模式 --> 
  14. <!-- 即内部元素触发的事件先在此处理,然后才交由内部元素进行处理 --> 
  15. <div @click.capture="doThis">...</div> 
  16.  
  17. <!-- 只当在 event.target 是当前元素自身时触发处理函数 --> 
  18. <!-- 即事件不是从内部元素触发的 --> 
  19. <div @click.self="doThat">...</div> 

 在渲染函数中设置

  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,表示该事件处理器只执行一次 
  16.    const Comp = () => h(Foo, { onFooOnce: onFoo }) 
  17.    const app = createApp(Comp); 
  18.    app.mount("#app"
  19. </script> 

以上两种方式都能生效的原因是,模板中的指令 v-on:welcome.once,经过编译后会转换为onWelcomeOnce,并且在 emit 函数中定义了 once 修饰符的处理规则:

  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 如何添加多个事件处理器

在模板中设置

  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.   } 

 在渲染函数中设置

  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 函数中含有多个事件处理器的处理逻辑:

  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 有什么区别?

在 Vue 2 中 $emit 方法是 Vue.prototype 对象上的属性,而 Vue 3 上的 $emit 是组件实例上的一个属性,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实例是一个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 中自定义事件背后的秘密。为了让大家能够更深入地掌握自定义事件的相关知识,阿宝哥从源码的角度分析了 $emit 方法的来源和自定义事件的处理流程。

在 Vue 3.0 进阶系列第一篇文章 Vue 3.0 进阶之指令探秘 中,我们已经介绍了指令相关的知识,有了这些基础,之后阿宝哥将带大家一起探索 Vue 3 双向绑定的原理,感兴趣的小伙伴不要错过哟。

四、参考资源

  • Vue 3 官网 - 事件处理
  • Vue 3 官网 - 自定义事件
  • Vue 3 官网 - 全局 API

 

责任编辑:姜华 来源: 全栈修仙之路
相关推荐

2021-02-26 05:19:20

Vue 3.0 VNode虚拟

2021-02-16 16:41:45

Vue项目指令

2021-02-28 20:41:18

Vue注入Angular

2021-02-19 23:07:02

Vue绑定组件

2021-02-22 21:49:33

Vue动态组件

2021-08-11 14:29:20

鸿蒙HarmonyOS应用

2009-08-04 09:56:46

C#事件处理自定义事件

2022-05-07 10:22:32

JavaScript自定义前端

2021-03-04 22:31:02

Vue进阶函数

2009-09-03 15:46:57

C#自定义事件

2010-08-13 11:34:54

Flex自定义事件

2020-04-15 15:35:29

vue.jsCSS开发

2022-02-22 13:14:30

Vue自定义指令注册

2021-07-05 15:35:47

Vue前端代码

2009-08-04 12:56:51

C#自定义事件

2010-08-12 09:45:33

jQuery自定义事件

2009-08-04 12:40:34

c#自定义事件

2009-08-04 13:53:58

C#委托类C#事件

2018-01-23 11:00:10

Hadoop3.0Yarn资源

2009-08-04 13:31:35

C#自定义事件
点赞
收藏

51CTO技术栈公众号