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

Vue 3.0 進(jìn)階之指令探秘

開發(fā) 項(xiàng)目管理
在 Vue 的項(xiàng)目中,我們經(jīng)常會(huì)遇到 v-if、v-show、v-for 或 v-model 這些內(nèi)置指令,它們?yōu)槲覀兲峁┝瞬煌墓δ堋3耸褂眠@些內(nèi)置指令之外,Vue 也允許注冊自定義指令。

[[381940]]

 本文轉(zhuǎn)載自微信公眾號(hào)「全棧修仙之路」,作者阿寶哥。轉(zhuǎn)載本文請聯(lián)系全棧修仙之路公眾號(hào)。  

在 Vue 的項(xiàng)目中,我們經(jīng)常會(huì)遇到 v-if、v-show、v-for 或 v-model 這些內(nèi)置指令,它們?yōu)槲覀兲峁┝瞬煌墓δ堋3耸褂眠@些內(nèi)置指令之外,Vue 也允許注冊自定義指令。

接下來,阿寶哥將使用 Vue 3 官方文檔 自定義指令 章節(jié)中使用的示例,來一步步揭開自定義指令背后的秘密。

提示:在閱讀本文前,建議您先閱讀 Vue 3 官方文檔 自定義指令 章節(jié)的內(nèi)容。

一、自定義指令

1、注冊全局自定義指令

  1. const app = Vue.createApp({}) 
  2.  
  3. // 注冊一個(gè)全局自定義指令 v-focus 
  4. app.directive('focus', { 
  5.   // 當(dāng)被綁定的元素掛載到 DOM 中時(shí)被調(diào)用 
  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.      // 當(dāng)被綁定的元素掛載到 DOM 中時(shí)被調(diào)用 
  10.      mounted(el) { 
  11.        el.focus() // 聚焦元素 
  12.      } 
  13.    }) 
  14.    app.mount('#app') // ③ 
  15. </script> 

當(dāng)頁面加載完成后,頁面中的輸入框元素將自動(dòng)獲得焦點(diǎn)。該示例的代碼比較簡單,主要包含 3 個(gè)步驟:創(chuàng)建 App 對(duì)象、注冊全局自定義指令和應(yīng)用掛載。其中創(chuàng)建 App 對(duì)象的細(xì)節(jié),阿寶哥會(huì)在后續(xù)的文章中單獨(dú)介紹,下面我們將重點(diǎn)分析其他 2 個(gè)步驟。首先我們先來分析注冊全局自定義指令的過程。

二、注冊全局自定義指令的過程

在以上示例中,我們使用 app 對(duì)象的 directive 方法來注冊全局自定義指令:

  1. app.directive('focus', { 
  2.   // 當(dāng)被綁定的元素掛載到 DOM 中時(shí)被調(diào)用 
  3.   mounted(el) { 
  4.     el.focus() // 聚焦元素 
  5.   } 
  6. }) 

當(dāng)然,除了注冊全局自定義指令外,我們也可以注冊局部指令,因?yàn)榻M件中也接受一個(gè) directives 的選項(xiàng):

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

對(duì)于以上示例來說,我們使用的 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 方法支持以下兩個(gè)參數(shù):

  • name:表示指令的名稱;
  • directive(可選):表示指令的定義。

name 參數(shù)比較簡單,所以我們重點(diǎn)分析 directive 參數(shù),該參數(shù)的類型是 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 類型屬于聯(lián)合類型,所以我們需要繼續(xù)分析 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 

該類型定義了對(duì)象類型的指令,對(duì)象上的每個(gè)屬性表示指令生命周期上的鉤子。而 FunctionDirective 類型則表示函數(shù)類型的指令:

  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 類型,我們再回顧一下前面的示例,相信你就會(huì)清晰很多:

  1. app.directive('focus', { 
  2.   // 當(dāng)被綁定的元素掛載到 DOM 中時(shí)觸發(fā) 
  3.   mounted(el) { 
  4.     el.focus() // 聚焦元素 
  5.   } 
  6. }) 

對(duì)于以上示例,當(dāng)我們調(diào)用 app.directive 方法注冊自定義 focus 指令時(shí),就會(huì)執(zhí)行以下邏輯:

  1. directive(name: string, directive?: Directive) { 
  2.   if (__DEV__) { // 避免自定義指令名稱,與已有的內(nèi)置指令名稱沖突 
  3.     validateDirectiveName(name
  4.   } 
  5.   if (!directive) { // 獲取name對(duì)應(yīng)的指令對(duì)象 
  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 

當(dāng) focus 指令注冊成功之后,該指令會(huì)被保存在 context 對(duì)象的 directives 屬性中,具體如下圖所示:

顧名思義 context 是表示應(yīng)用的上下文對(duì)象,那么該對(duì)象是如何創(chuàng)建的呢?其實(shí),該對(duì)象是通過 createAppContext 函數(shù)來創(chuàng)建的:

  1. const context = createAppContext() 

而 createAppContext 函數(shù)被定義在 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.   } 

看到這里,是不是覺得注冊全局自定義指令的內(nèi)部處理邏輯其實(shí)挺簡單的。那么對(duì)于已注冊的 focus 指令,何時(shí)會(huì)被調(diào)用呢?要回答這個(gè)問題,我們就需要分析另一個(gè)步驟 ——應(yīng)用掛載。

三、應(yīng)用掛載的過程

為了更加直觀地了解應(yīng)用掛載的過程,阿寶哥利用 Chrome 開發(fā)者工具,記錄了應(yīng)用掛載的主要過程:

通過上圖,我們就可以知道應(yīng)用掛載期間所經(jīng)歷的主要過程。此外,從圖中我們也發(fā)現(xiàn)了一個(gè)與指令相關(guān)的函數(shù) resolveDirective。很明顯,該函數(shù)用于解析指令,且該函數(shù)在render 方法中會(huì)被調(diào)用。在源碼中,我們找到了該函數(shù)的定義:

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

在 resolveDirective 函數(shù)內(nèi)部,會(huì)繼續(xù)調(diào)用 resolveAsset 函數(shù)來執(zhí)行具體的解析操作。在分析 resolveAsset 函數(shù)的具體實(shí)現(xiàn)之前,我們在 resolveDirective 函數(shù)內(nèi)部加個(gè)斷點(diǎn),來一睹 render 方法的 “芳容”:

在上圖中,我們看到了與 focus 指令相關(guān)的 _resolveDirective("focus") 函數(shù)調(diào)用。前面我們已經(jīng)知道在 resolveDirective 函數(shù)內(nèi)部會(huì)繼續(xù)調(diào)用 resolveAsset 函數(shù),該函數(shù)的具體實(shí)現(xiàn)如下:

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

因?yàn)樽?focus 指令時(shí),使用的是全局注冊的方式,所以解析的過程會(huì)執(zhí)行 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.   ) 

分析完以上的處理流程,我們可以知道在解析全局注冊的指令時(shí),會(huì)通過 resolve 函數(shù)從應(yīng)用的上下文對(duì)象中獲取已注冊的指令對(duì)象。在獲取到 _directive_focus 指令對(duì)象后,render 方法內(nèi)部會(huì)繼續(xù)調(diào)用 _withDirectives 函數(shù),用于把指令添加到 VNode 對(duì)象上,該函數(shù)被定義在 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 // 獲取當(dāng)前渲染的實(shí)例 
  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 時(shí),觸發(fā)相同行為,而不關(guān)系其他的鉤子函數(shù) 
  12.     if (isFunction(dir)) { // 處理函數(shù)類型指令 
  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 

因?yàn)橐粋€(gè)節(jié)點(diǎn)上可能會(huì)應(yīng)用多個(gè)指令,所以 withDirectives 函數(shù)在 VNode 對(duì)象上定義了一個(gè) dirs 屬性且該屬性值為數(shù)組。對(duì)于前面的示例來說,在調(diào)用 withDirectives 函數(shù)之后,VNode 對(duì)象上就會(huì)新增一個(gè) dirs 屬性,具體如下圖所示:

通過上面的分析,我們已經(jīng)知道在組件的 render 方法中,我們會(huì)通過 withDirectives函數(shù)把指令注冊對(duì)應(yīng)的 VNode 對(duì)象上。那么 focus 指令上定義的鉤子什么時(shí)候會(huì)被調(diào)用呢?在繼續(xù)分析之前,我們先來介紹一下指令對(duì)象所支持的鉤子函數(shù)。

一個(gè)指令定義對(duì)象可以提供如下幾個(gè)鉤子函數(shù) (均為可選):

  • created:在綁定元素的屬性或事件監(jiān)聽器被應(yīng)用之前調(diào)用。
  • beforeMount:當(dāng)指令第一次綁定到元素并且在掛載父組件之前調(diào)用。
  • mounted:在綁定元素的父組件被掛載后調(diào)用。
  • beforeUpdate:在更新包含組件的 VNode 之前調(diào)用。
  • updated:在包含組件的 VNode 及其子組件的 VNode 更新后調(diào)用。
  • beforeUnmount:在卸載綁定元素的父組件之前調(diào)用。
  • unmounted:當(dāng)指令與元素解除綁定且父組件已卸載時(shí),只調(diào)用一次。

介紹完這些鉤子函數(shù)之后,我們再來回顧一下前面介紹的 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 指令上定義的鉤子什么時(shí)候被調(diào)用。同樣,阿寶哥在focus 指令的 mounted 方法中加個(gè)斷點(diǎn):

在圖中右側(cè)的調(diào)用棧中,我們看到了 invokeDirectiveHook 函數(shù),很明顯該函數(shù)的作用就是調(diào)用指令上已注冊的鉤子。出于篇幅考慮,具體的細(xì)節(jié)阿寶哥就不繼續(xù)介紹了,感興趣的小伙伴可以自行斷點(diǎn)調(diào)試一下。

四、阿寶哥有話說

4.1 Vue 3 有哪些內(nèi)置指令?

在介紹注冊全局自定義指令的過程中,我們看到了一個(gè) validateDirectiveName 函數(shù),該函數(shù)用于驗(yàn)證自定義指令的名稱,從而避免自定義指令名稱,與已有的內(nèi)置指令名稱沖突。

  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 函數(shù)內(nèi)部,會(huì)通過 isBuiltInDirective(name) 語句來判斷是否為內(nèi)置指令:

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

以上代碼中的 makeMap 函數(shù),用于生成一個(gè) map 對(duì)象(Object.create(null))并返回一個(gè)函數(shù),用于檢測某個(gè) key 是否存在 map 對(duì)象中。另外,通過以上代碼,我們就可以很清楚地了解 Vue 3 中為我們提供了哪些內(nèi)置指令。

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 時(shí)觸發(fā)相同行為,而不關(guān)心其他的鉤子函數(shù)。那么你可以通過將回調(diào)函數(shù)傳遞給指令來實(shí)現(xiàn):

  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 注冊全局指令與局部指令有什么區(qū)別?

注冊全局指令

  1. app.directive('focus', { 
  2.   // 當(dāng)被綁定的元素掛載到 DOM 中時(shí)被調(diào)用 
  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 內(nèi)置指令和自定義指令生成的渲染函數(shù)有什么區(qū)別?

要了解內(nèi)置指令和自定義指令生成的渲染函數(shù)的區(qū)別,阿寶哥以 v-if 、v-show 內(nèi)置指令和 v-focus 自定義指令為例,然后使用 Vue 3 Template Explorer 這個(gè)在線工具來編譯生成渲染函數(shù):

v-if 內(nèi)置指令

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

對(duì)于 v-if 指令來說,在編譯后會(huì)通過 ?: 三目運(yùn)算符來實(shí)現(xiàn)動(dòng)態(tài)創(chuàng)建節(jié)點(diǎn)的功能。

v-show 內(nèi)置指令

  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 類型的指令,該指令內(nèi)部定義了beforeMount、mounted、updated 和 beforeUnmount 四個(gè)鉤子。

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

通過對(duì)比 v-focus 與 v-show 指令生成的渲染函數(shù),我們可知 v-focus 自定義指令與v-show 內(nèi)置指令都會(huì)通過 withDirectives 函數(shù),把指令注冊到 VNode 對(duì)象上。而自定義指令相比內(nèi)置指令來說,會(huì)多一個(gè)指令解析的過程。

此外,如果在 input 元素上,同時(shí)應(yīng)用了 v-show 和 v-focus 指令,則在調(diào)用 _withDirectives 函數(shù)時(shí),將使用二維數(shù)組:

  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 如何在渲染函數(shù)中應(yīng)用指令?

除了在模板中應(yīng)用指令之外,利用前面介紹的 withDirectives 函數(shù),我們可以很方便地在渲染函數(shù)中應(yīng)用指定的指令:

  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 中如何自定義指令、如何注冊全局和局部指令。為了讓大家能夠更深入地掌握自定義指令的相關(guān)知識(shí),阿寶哥從源碼的角度分析了指令的注冊和應(yīng)用過程。

在后續(xù)的文章中,阿寶哥將會(huì)介紹一些特殊的指令,當(dāng)然也會(huì)重點(diǎn)分析一下雙向綁定的原理,感興趣的小伙伴不要錯(cuò)過喲。

五、參考資源

  • Vue 3 官網(wǎng) - 自定義指令
  • Vue 3 官網(wǎng) - 應(yīng)用 API

 

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

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動(dòng)態(tài)組件

2021-02-18 08:19:21

Vue自定義Vue 3.0

2021-03-04 22:31:02

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

2021-03-09 22:29:46

Vue 響應(yīng)式API

2021-03-08 00:08:29

Vue應(yīng)用掛載

2010-05-11 16:22:40

2020-10-13 08:24:31

Vue3.0系列

2020-04-22 14:15:32

Vue 3.0語法前端

2022-05-06 15:55:54

AT指令鴻蒙

2025-01-22 13:05:58

2011-05-20 09:43:23

JDK7

2011-05-20 09:35:22

JDK7

2022-03-09 09:00:41

SwiftUI視圖生成器Swift

2009-06-30 16:46:45

Criteria進(jìn)階查

2022-03-01 09:01:56

SwiftUI動(dòng)畫進(jìn)階Canvas

2020-08-25 09:50:35

Vue3.0命令前端

2022-02-06 22:13:47

VueVue3.0Vue項(xiàng)目
點(diǎn)贊
收藏

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