Vue 3.0 进阶之指令探秘

开发 项目管理
在 Vue 的项目中,我们经常会遇到 v-if、v-show、v-for 或 v-model 这些内置指令,它们为我们提供了不同的功能。除了使用这些内置指令之外,Vue 也允许注册自定义指令。

[[381940]]

 本文转载自微信公众号「全栈修仙之路」,作者阿宝哥。转载本文请联系全栈修仙之路公众号。  

在 Vue 的项目中,我们经常会遇到 v-if、v-show、v-for 或 v-model 这些内置指令,它们为我们提供了不同的功能。除了使用这些内置指令之外,Vue 也允许注册自定义指令。

接下来,阿宝哥将使用 Vue 3 官方文档 自定义指令 章节中使用的示例,来一步步揭开自定义指令背后的秘密。

提示:在阅读本文前,建议您先阅读 Vue 3 官方文档 自定义指令 章节的内容。

一、自定义指令

1、注册全局自定义指令

  1. const app = Vue.createApp({}) 
  2.  
  3. // 注册一个全局自定义指令 v-focus 
  4. app.directive('focus', { 
  5.   // 当被绑定的元素挂载到 DOM 中时被调用 
  6.   mounted(el) { 
  7.     // 聚焦元素 
  8.     el.focus() 
  9.   } 
  10. }) 

2、使用全局自定义指令

  1. <div id="app"
  2.    <input v-focus /> 
  3. </div> 

3、完整的使用示例

  1. <div id="app"
  2.    <input v-focus /> 
  3. </div> 
  4. <script> 
  5.    const { createApp } = Vue 
  6.     
  7.    const app = Vue.createApp({}) // ① 
  8.    app.directive('focus', { // ②  
  9.      // 当被绑定的元素挂载到 DOM 中时被调用 
  10.      mounted(el) { 
  11.        el.focus() // 聚焦元素 
  12.      } 
  13.    }) 
  14.    app.mount('#app') // ③ 
  15. </script> 

当页面加载完成后,页面中的输入框元素将自动获得焦点。该示例的代码比较简单,主要包含 3 个步骤:创建 App 对象、注册全局自定义指令和应用挂载。其中创建 App 对象的细节,阿宝哥会在后续的文章中单独介绍,下面我们将重点分析其他 2 个步骤。首先我们先来分析注册全局自定义指令的过程。

二、注册全局自定义指令的过程

在以上示例中,我们使用 app 对象的 directive 方法来注册全局自定义指令:

  1. app.directive('focus', { 
  2.   // 当被绑定的元素挂载到 DOM 中时被调用 
  3.   mounted(el) { 
  4.     el.focus() // 聚焦元素 
  5.   } 
  6. }) 

当然,除了注册全局自定义指令外,我们也可以注册局部指令,因为组件中也接受一个 directives 的选项:

  1. directives: { 
  2.   focus: { 
  3.     mounted(el) { 
  4.       el.focus() 
  5.     } 
  6.   } 

对于以上示例来说,我们使用的 app.directive 方法被定义在 runtime-core/src/apiCreateApp.ts 文件中:

  1. // packages/runtime-core/src/apiCreateApp.ts 
  2. export function createAppAPI<HostElement>( 
  3.   render: RootRenderFunction, 
  4.   hydrate?: RootHydrateFunction 
  5. ): CreateAppFunction<HostElement> { 
  6.   return function createApp(rootComponent, rootProps = null) { 
  7.     const context = createAppContext() 
  8.     let isMounted = false 
  9.  
  10.     const app: App = (context.app = { 
  11.       // 省略部分代码 
  12.       _context: context, 
  13.        
  14.       // 用于注册或检索全局指令。 
  15.       directive(name: string, directive?: Directive) { 
  16.         if (__DEV__) { 
  17.           validateDirectiveName(name
  18.         } 
  19.         if (!directive) { 
  20.           return context.directives[nameas any 
  21.         } 
  22.         if (__DEV__ && context.directives[name]) { 
  23.           warn(`Directive "${name}" has already been registered in target app.`) 
  24.         } 
  25.         context.directives[name] = directive 
  26.         return app 
  27.       }, 
  28.  
  29.     return app 
  30.   } 

通过观察以上代码,我们可以知道 directive 方法支持以下两个参数:

  • name:表示指令的名称;
  • directive(可选):表示指令的定义。

name 参数比较简单,所以我们重点分析 directive 参数,该参数的类型是 Directive类型:

  1. // packages/runtime-core/src/directives.ts 
  2. export type Directive<T = any, V = any> = 
  3.   | ObjectDirective<T, V> 
  4.   | FunctionDirective<T, V> 

由上可知 Directive 类型属于联合类型,所以我们需要继续分析 ObjectDirective 和 FunctionDirective 类型。这里我们先来看一下 ObjectDirective 类型的定义:

  1. // packages/runtime-core/src/directives.ts 
  2. export interface ObjectDirective<T = any, V = any> { 
  3.   created?: DirectiveHook<T, null, V> 
  4.   beforeMount?: DirectiveHook<T, null, V> 
  5.   mounted?: DirectiveHook<T, null, V> 
  6.   beforeUpdate?: DirectiveHook<T, VNode<any, T>, V> 
  7.   updated?: DirectiveHook<T, VNode<any, T>, V> 
  8.   beforeUnmount?: DirectiveHook<T, null, V> 
  9.   unmounted?: DirectiveHook<T, null, V> 
  10.   getSSRProps?: SSRDirectiveHook 

该类型定义了对象类型的指令,对象上的每个属性表示指令生命周期上的钩子。而 FunctionDirective 类型则表示函数类型的指令:

  1. // packages/runtime-core/src/directives.ts 
  2. export type FunctionDirective<T = any, V = any> = DirectiveHook<T, any, V> 
  3.                                
  4. export type DirectiveHook<T = any, Prev = VNode<any, T> | null, V = any> = ( 
  5.   el: T, 
  6.   binding: DirectiveBinding<V>, 
  7.   vnode: VNode<any, T>, 
  8.   prevVNode: Prev 
  9. ) => void               

介绍完 Directive 类型,我们再回顾一下前面的示例,相信你就会清晰很多:

  1. app.directive('focus', { 
  2.   // 当被绑定的元素挂载到 DOM 中时触发 
  3.   mounted(el) { 
  4.     el.focus() // 聚焦元素 
  5.   } 
  6. }) 

对于以上示例,当我们调用 app.directive 方法注册自定义 focus 指令时,就会执行以下逻辑:

  1. directive(name: string, directive?: Directive) { 
  2.   if (__DEV__) { // 避免自定义指令名称,与已有的内置指令名称冲突 
  3.     validateDirectiveName(name
  4.   } 
  5.   if (!directive) { // 获取name对应的指令对象 
  6.     return context.directives[nameas any 
  7.   } 
  8.   if (__DEV__ && context.directives[name]) { 
  9.     warn(`Directive "${name}" has already been registered in target app.`) 
  10.   } 
  11.   context.directives[name] = directive // 注册全局指令 
  12.   return app 

当 focus 指令注册成功之后,该指令会被保存在 context 对象的 directives 属性中,具体如下图所示:

顾名思义 context 是表示应用的上下文对象,那么该对象是如何创建的呢?其实,该对象是通过 createAppContext 函数来创建的:

  1. const context = createAppContext() 

而 createAppContext 函数被定义在 runtime-core/src/apiCreateApp.ts 文件中:

  1. // packages/runtime-core/src/apiCreateApp.ts 
  2. export function createAppContext(): AppContext { 
  3.   return { 
  4.     app: null as any
  5.     config: { 
  6.       isNativeTag: NO
  7.       performance: false
  8.       globalProperties: {}, 
  9.       optionMergeStrategies: {}, 
  10.       isCustomElement: NO
  11.       errorHandler: undefined, 
  12.       warnHandler: undefined 
  13.     }, 
  14.     mixins: [], 
  15.     components: {}, 
  16.     directives: {}, 
  17.     provides: Object.create(null
  18.   } 

看到这里,是不是觉得注册全局自定义指令的内部处理逻辑其实挺简单的。那么对于已注册的 focus 指令,何时会被调用呢?要回答这个问题,我们就需要分析另一个步骤 ——应用挂载。

三、应用挂载的过程

为了更加直观地了解应用挂载的过程,阿宝哥利用 Chrome 开发者工具,记录了应用挂载的主要过程:

通过上图,我们就可以知道应用挂载期间所经历的主要过程。此外,从图中我们也发现了一个与指令相关的函数 resolveDirective。很明显,该函数用于解析指令,且该函数在render 方法中会被调用。在源码中,我们找到了该函数的定义:

  1. // packages/runtime-core/src/helpers/resolveAssets.ts 
  2. export function resolveDirective(name: string): Directive | undefined { 
  3.   return resolveAsset(DIRECTIVES, name

在 resolveDirective 函数内部,会继续调用 resolveAsset 函数来执行具体的解析操作。在分析 resolveAsset 函数的具体实现之前,我们在 resolveDirective 函数内部加个断点,来一睹 render 方法的 “芳容”:

在上图中,我们看到了与 focus 指令相关的 _resolveDirective("focus") 函数调用。前面我们已经知道在 resolveDirective 函数内部会继续调用 resolveAsset 函数,该函数的具体实现如下:

  1. // packages/runtime-core/src/helpers/resolveAssets.ts 
  2. function resolveAsset( 
  3.   type: typeof COMPONENTS | typeof DIRECTIVES, 
  4.   name: string, 
  5.   warnMissing = true 
  6. ) { 
  7.   const instance = currentRenderingInstance || currentInstance 
  8.   if (instance) { 
  9.     const Component = instance.type 
  10.     // 省略解析组件的处理逻辑 
  11.     const res = 
  12.       // 局部注册 
  13.       resolve(instance[type] || (Component as ComponentOptions)[type], name) || 
  14.       // 全局注册 
  15.       resolve(instance.appContext[type], name
  16.     return res 
  17.   } else if (__DEV__) { 
  18.     warn( 
  19.       `resolve${capitalize(type.slice(0, -1))} ` + 
  20.         `can only be used in render() or setup().` 
  21.     ) 
  22.   } 

因为注册 focus 指令时,使用的是全局注册的方式,所以解析的过程会执行 resolve(instance.appContext[type], name) 该语句,其中 resolve 方法的定义如下:

  1. function resolve(registry: Record<string, any> | undefined, name: string) { 
  2.   return ( 
  3.     registry && 
  4.     (registry[name] || 
  5.       registry[camelize(name)] || 
  6.       registry[capitalize(camelize(name))]) 
  7.   ) 

分析完以上的处理流程,我们可以知道在解析全局注册的指令时,会通过 resolve 函数从应用的上下文对象中获取已注册的指令对象。在获取到 _directive_focus 指令对象后,render 方法内部会继续调用 _withDirectives 函数,用于把指令添加到 VNode 对象上,该函数被定义在 runtime-core/src/directives.ts 文件中:

  1. // packages/runtime-core/src/directives.ts 
  2. export function withDirectives<T extends VNode>( 
  3.   vnode: T, 
  4.   directives: DirectiveArguments 
  5. ): T { 
  6.   const internalInstance = currentRenderingInstance // 获取当前渲染的实例 
  7.   const instance = internalInstance.proxy 
  8.   const bindings: DirectiveBinding[] = vnode.dirs || (vnode.dirs = []) 
  9.   for (let i = 0; i < directives.length; i++) { 
  10.     let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i] 
  11.     // 在 mounted 和 updated 时,触发相同行为,而不关系其他的钩子函数 
  12.     if (isFunction(dir)) { // 处理函数类型指令 
  13.       dir = { 
  14.         mounted: dir, 
  15.         updated: dir 
  16.       } as ObjectDirective 
  17.     } 
  18.     bindings.push({ 
  19.       dir, 
  20.       instance, 
  21.       value, 
  22.       oldValue: void 0, 
  23.       arg, 
  24.       modifiers 
  25.     }) 
  26.   } 
  27.   return vnode 

因为一个节点上可能会应用多个指令,所以 withDirectives 函数在 VNode 对象上定义了一个 dirs 属性且该属性值为数组。对于前面的示例来说,在调用 withDirectives 函数之后,VNode 对象上就会新增一个 dirs 属性,具体如下图所示:

通过上面的分析,我们已经知道在组件的 render 方法中,我们会通过 withDirectives函数把指令注册对应的 VNode 对象上。那么 focus 指令上定义的钩子什么时候会被调用呢?在继续分析之前,我们先来介绍一下指令对象所支持的钩子函数。

一个指令定义对象可以提供如下几个钩子函数 (均为可选):

  • created:在绑定元素的属性或事件监听器被应用之前调用。
  • beforeMount:当指令第一次绑定到元素并且在挂载父组件之前调用。
  • mounted:在绑定元素的父组件被挂载后调用。
  • beforeUpdate:在更新包含组件的 VNode 之前调用。
  • updated:在包含组件的 VNode 及其子组件的 VNode 更新后调用。
  • beforeUnmount:在卸载绑定元素的父组件之前调用。
  • unmounted:当指令与元素解除绑定且父组件已卸载时,只调用一次。

介绍完这些钩子函数之后,我们再来回顾一下前面介绍的 ObjectDirective 类型:

  1. // packages/runtime-core/src/directives.ts 
  2. export interface ObjectDirective<T = any, V = any> { 
  3.   created?: DirectiveHook<T, null, V> 
  4.   beforeMount?: DirectiveHook<T, null, V> 
  5.   mounted?: DirectiveHook<T, null, V> 
  6.   beforeUpdate?: DirectiveHook<T, VNode<any, T>, V> 
  7.   updated?: DirectiveHook<T, VNode<any, T>, V> 
  8.   beforeUnmount?: DirectiveHook<T, null, V> 
  9.   unmounted?: DirectiveHook<T, null, V> 
  10.   getSSRProps?: SSRDirectiveHook 

好的,接下来我们来分析一下 focus 指令上定义的钩子什么时候被调用。同样,阿宝哥在focus 指令的 mounted 方法中加个断点:

在图中右侧的调用栈中,我们看到了 invokeDirectiveHook 函数,很明显该函数的作用就是调用指令上已注册的钩子。出于篇幅考虑,具体的细节阿宝哥就不继续介绍了,感兴趣的小伙伴可以自行断点调试一下。

四、阿宝哥有话说

4.1 Vue 3 有哪些内置指令?

在介绍注册全局自定义指令的过程中,我们看到了一个 validateDirectiveName 函数,该函数用于验证自定义指令的名称,从而避免自定义指令名称,与已有的内置指令名称冲突。

  1. // packages/runtime-core/src/directives.ts 
  2. export function validateDirectiveName(name: string) { 
  3.   if (isBuiltInDirective(name)) { 
  4.     warn('Do not use built-in directive ids as custom directive id: ' + name
  5.   } 

在 validateDirectiveName 函数内部,会通过 isBuiltInDirective(name) 语句来判断是否为内置指令:

  1. const isBuiltInDirective = /*#__PURE__*/ makeMap( 
  2.   'bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text' 

以上代码中的 makeMap 函数,用于生成一个 map 对象(Object.create(null))并返回一个函数,用于检测某个 key 是否存在 map 对象中。另外,通过以上代码,我们就可以很清楚地了解 Vue 3 中为我们提供了哪些内置指令。

4.2 指令有几种类型?

在 Vue 3 中指令分为 ObjectDirective 和 FunctionDirective 两种类型:

  1. // packages/runtime-core/src/directives.ts 
  2. export type Directive<T = any, V = any> = 
  3.   | ObjectDirective<T, V> 
  4.   | FunctionDirective<T, V> 

ObjectDirective

  1. export interface ObjectDirective<T = any, V = any> { 
  2.   created?: DirectiveHook<T, null, V> 
  3.   beforeMount?: DirectiveHook<T, null, V> 
  4.   mounted?: DirectiveHook<T, null, V> 
  5.   beforeUpdate?: DirectiveHook<T, VNode<any, T>, V> 
  6.   updated?: DirectiveHook<T, VNode<any, T>, V> 
  7.   beforeUnmount?: DirectiveHook<T, null, V> 
  8.   unmounted?: DirectiveHook<T, null, V> 
  9.   getSSRProps?: SSRDirectiveHook 

FunctionDirective

  1. export type FunctionDirective<T = any, V = any> = DirectiveHook<T, any, V> 
  2.                                
  3. export type DirectiveHook<T = any, Prev = VNode<any, T> | null, V = any> = ( 
  4.   el: T, 
  5.   binding: DirectiveBinding<V>, 
  6.   vnode: VNode<any, T>, 
  7.   prevVNode: Prev 
  8. ) => void 

如果你想在 mounted 和 updated 时触发相同行为,而不关心其他的钩子函数。那么你可以通过将回调函数传递给指令来实现:

  1. app.directive('pin', (el, binding) => { 
  2.   el.style.position = 'fixed' 
  3.   const s = binding.arg || 'top' 
  4.   el.style[s] = binding.value + 'px' 
  5. }) 

4.3 注册全局指令与局部指令有什么区别?

注册全局指令

  1. app.directive('focus', { 
  2.   // 当被绑定的元素挂载到 DOM 中时被调用 
  3.   mounted(el) { 
  4.     el.focus() // 聚焦元素 
  5.   } 
  6. }); 

注册局部指令

  1. const Component = defineComponent({ 
  2.   directives: { 
  3.     focus: { 
  4.       mounted(el) { 
  5.         el.focus() 
  6.       } 
  7.     } 
  8.   }, 
  9.   render() { 
  10.     const { directives } = this.$options; 
  11.     return [withDirectives(h('input'), [[directives.focus, ]])] 
  12.   } 
  13. }); 

解析全局注册和局部注册的指令

  1. // packages/runtime-core/src/helpers/resolveAssets.ts 
  2. function resolveAsset( 
  3.   type: typeof COMPONENTS | typeof DIRECTIVES, 
  4.   name: string, 
  5.   warnMissing = true 
  6. ) { 
  7.   const instance = currentRenderingInstance || currentInstance 
  8.   if (instance) { 
  9.     const Component = instance.type 
  10.     // 省略解析组件的处理逻辑 
  11.     const res = 
  12.       // 局部注册 
  13.       resolve(instance[type] || (Component as ComponentOptions)[type], name) || 
  14.       // 全局注册 
  15.       resolve(instance.appContext[type], name
  16.     return res 
  17.   } 

4.4 内置指令和自定义指令生成的渲染函数有什么区别?

要了解内置指令和自定义指令生成的渲染函数的区别,阿宝哥以 v-if 、v-show 内置指令和 v-focus 自定义指令为例,然后使用 Vue 3 Template Explorer 这个在线工具来编译生成渲染函数:

v-if 内置指令

  1. <input v-if="isShow" /> 
  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, createCommentVNode: _createCommentVNode } = _Vue 
  8.  
  9.     return isShow 
  10.       ? (_openBlock(), _createBlock("input", { key: 0 })) 
  11.       : _createCommentVNode("v-if"true
  12.   } 

对于 v-if 指令来说,在编译后会通过 ?: 三目运算符来实现动态创建节点的功能。

v-show 内置指令

  1. <input v-show="isShow" /> 
  2.    
  3. const _Vue = Vue 
  4. return function render(_ctx, _cache, $props, $setup, $data, $options) { 
  5.   with (_ctx) { 
  6.     const { vShow: _vShow, createVNode: _createVNode, withDirectives: _withDirectives,  
  7.       openBlock: _openBlock, createBlock: _createBlock } = _Vue 
  8.  
  9.     return _withDirectives((_openBlock(), _createBlock("input"nullnull, 512 /* NEED_PATCH */)), [ 
  10.       [_vShow, isShow] 
  11.     ]) 
  12.   } 

以上示例中的 vShow 指令被定义在 packages/runtime-dom/src/directives/vShow.ts文件中,该指令属于 ObjectDirective 类型的指令,该指令内部定义了beforeMount、mounted、updated 和 beforeUnmount 四个钩子。

v-focus 自定义指令

  1. <input v-focus /> 
  2.  
  3. const _Vue = Vue 
  4. return function render(_ctx, _cache, $props, $setup, $data, $options) { 
  5.   with (_ctx) { 
  6.     const { resolveDirective: _resolveDirective, createVNode: _createVNode,  
  7.       withDirectives: _withDirectives, openBlock: _openBlock, createBlock: _createBlock } = _Vue 
  8.  
  9.     const _directive_focus = _resolveDirective("focus"
  10.     return _withDirectives((_openBlock(), _createBlock("input"nullnull, 512 /* NEED_PATCH */)), [ 
  11.       [_directive_focus] 
  12.     ]) 
  13.   } 

通过对比 v-focus 与 v-show 指令生成的渲染函数,我们可知 v-focus 自定义指令与v-show 内置指令都会通过 withDirectives 函数,把指令注册到 VNode 对象上。而自定义指令相比内置指令来说,会多一个指令解析的过程。

此外,如果在 input 元素上,同时应用了 v-show 和 v-focus 指令,则在调用 _withDirectives 函数时,将使用二维数组:

  1. <input v-show="isShow" v-focus /> 
  2.  
  3. const _Vue = Vue 
  4. return function render(_ctx, _cache, $props, $setup, $data, $options) { 
  5.   with (_ctx) { 
  6.     const { vShow: _vShow, resolveDirective: _resolveDirective, createVNode: _createVNode,  
  7.       withDirectives: _withDirectives, openBlock: _openBlock, createBlock: _createBlock } = _Vue 
  8.  
  9.     const _directive_focus = _resolveDirective("focus"
  10.     return _withDirectives((_openBlock(), _createBlock("input"nullnull, 512 /* NEED_PATCH */)), [ 
  11.       [_vShow, isShow], 
  12.       [_directive_focus] 
  13.     ]) 
  14.   } 

4.5 如何在渲染函数中应用指令?

除了在模板中应用指令之外,利用前面介绍的 withDirectives 函数,我们可以很方便地在渲染函数中应用指定的指令:

  1. <div id="app"></div> 
  2. <script> 
  3.    const { createApp, h, vShow, defineComponent, withDirectives } = Vue 
  4.    const Component = defineComponent({ 
  5.      data() { 
  6.        return { value: true } 
  7.      }, 
  8.      render() { 
  9.        return [withDirectives(h('div''我是阿宝哥'), [[vShow, this.value]])] 
  10.      } 
  11.    }); 
  12.    const app = Vue.createApp(Component) 
  13.    app.mount('#app'
  14. </script> 

本文阿宝哥主要介绍了在 Vue 3 中如何自定义指令、如何注册全局和局部指令。为了让大家能够更深入地掌握自定义指令的相关知识,阿宝哥从源码的角度分析了指令的注册和应用过程。

在后续的文章中,阿宝哥将会介绍一些特殊的指令,当然也会重点分析一下双向绑定的原理,感兴趣的小伙伴不要错过哟。

五、参考资源

  • Vue 3 官网 - 自定义指令
  • Vue 3 官网 - 应用 API

 

责任编辑:武晓燕 来源: 全栈修仙之路
相关推荐

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动态组件

2021-02-18 08:19:21

Vue自定义Vue 3.0

2021-03-04 22:31:02

Vue进阶函数

2021-03-09 22:29:46

Vue 响应式API

2021-03-08 00:08:29

Vue应用挂载

2010-05-11 16:22:40

2020-10-13 08:24:31

Vue3.0系列

2022-05-06 15:55:54

AT指令鸿蒙

2020-04-22 14:15:32

Vue 3.0语法前端

2011-05-20 09:35:22

JDK7

2011-05-20 09:43:23

JDK7

2022-02-22 13:14:30

Vue自定义指令注册

2020-08-25 09:50:35

Vue3.0命令前端

2022-02-06 22:13:47

VueVue3.0Vue项目

2013-04-17 10:06:55

Google GlasMirror API

2021-07-05 15:35:47

Vue前端代码

2021-11-30 08:19:43

Vue3 插件Vue应用
点赞
收藏

51CTO技术栈公众号