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

聊聊Vue3 的模板編譯優(yōu)化

開發(fā) 前端
Vue3 正式發(fā)布已經(jīng)有一段時間了,前段時間寫了一篇文章(《Vue 模板編譯原理》)分析 Vue 的模板編譯原理。今天的文章打算學(xué)習(xí)下 Vue3 下的模板編譯與 Vue2 下的差異,以及 VDOM 下 Diff 算法的優(yōu)化。

[[351771]]

Vue3 正式發(fā)布已經(jīng)有一段時間了,前段時間寫了一篇文章(《Vue 模板編譯原理》)分析 Vue 的模板編譯原理。今天的文章打算學(xué)習(xí)下 Vue3 下的模板編譯與 Vue2 下的差異,以及 VDOM 下 Diff 算法的優(yōu)化。

編譯入口

了解過 Vue3 的同學(xué)肯定知道 Vue3 引入了新的組合 Api,在組件 mount 階段會調(diào)用 setup 方法,之后會判斷 render 方法是否存在,如果不存在會調(diào)用 compile 方法將 template 轉(zhuǎn)化為 render。

  1. // packages/runtime-core/src/renderer.ts 
  2. const mountComponent = (initialVNode, container) => { 
  3.   const instance = ( 
  4.     initialVNode.component = createComponentInstance( 
  5.       // ...params 
  6.     ) 
  7.   ) 
  8.   // 調(diào)用 setup 
  9.   setupComponent(instance) 
  10.  
  11. // packages/runtime-core/src/component.ts 
  12. let compile 
  13. export function registerRuntimeCompiler(_compile) { 
  14.   compile = _compile 
  15. export function setupComponent(instance) { 
  16.   const Component = instance.type 
  17.   const { setup } = Component 
  18.   if (setup) { 
  19.     // ...調(diào)用 setup 
  20.   } 
  21.   if (compile && Component.template && !Component.render) { 
  22.    // 如果沒有 render 方法 
  23.     // 調(diào)用 compile 將 template 轉(zhuǎn)為 render 方法 
  24.     Component.render = compile(Component.template, {...}) 
  25.   } 

這部分都是 runtime-core 中的代碼,之前的文章有講過 Vue 分為完整版和 runtime 版本。如果使用 vue-loader 處理 .vue 文件,一般都會將 .vue 文件中的 template 直接處理成 render 方法。

  1. //  需要編譯器 
  2. Vue.createApp({ 
  3.   template: '<div>{{ hi }}</div>' 
  4. }) 
  5.  
  6. // 不需要 
  7. Vue.createApp({ 
  8.   render() { 
  9.     return Vue.h('div', {}, this.hi) 
  10.   } 
  11. }) 

完整版與 runtime 版的差異就是,完整版會引入 compile 方法,如果是 vue-cli 生成的項目就會抹去這部分代碼,將 compile 過程都放到打包的階段,以此優(yōu)化性能。runtime-dom 中提供了 registerRuntimeCompiler 方法用于注入 compile 方法。

主流程

在完整版的 index.js 中,調(diào)用了 registerRuntimeCompiler 將 compile 進行注入,接下來我們看看注入的 compile 方法主要做了什么。

  1. // packages/vue/src/index.ts 
  2. import { compile } from '@vue/compiler-dom' 
  3.  
  4. // 編譯緩存 
  5. const compileCache = Object.create(null
  6.  
  7. // 注入 compile 方法 
  8. function compileToFunction( 
  9.  // 模板 
  10.   template: string | HTMLElement, 
  11.   // 編譯配置 
  12.   options?: CompilerOptions 
  13. ): RenderFunction { 
  14.   if (!isString(template)) { 
  15.     // 如果 template 不是字符串 
  16.     // 則認為是一個 DOM 節(jié)點,獲取 innerHTML 
  17.     if (template.nodeType) { 
  18.       template = template.innerHTML 
  19.     } else { 
  20.       return NOOP 
  21.     } 
  22.   } 
  23.  
  24.   // 如果緩存中存在,直接從緩存中獲取 
  25.   const key = template 
  26.   const cached = compileCache[key
  27.   if (cached) { 
  28.     return cached 
  29.   } 
  30.  
  31.   // 如果是 ID 選擇器,這獲取 DOM 元素后,取 innerHTML 
  32.   if (template[0] === '#') { 
  33.     const el = document.querySelector(template) 
  34.     template = el ? el.innerHTML : '' 
  35.   } 
  36.  
  37.   // 調(diào)用 compile 獲取 render code 
  38.   const { code } = compile( 
  39.     template, 
  40.     options 
  41.   ) 
  42.  
  43.   // 將 render code 轉(zhuǎn)化為 function 
  44.   const render = new Function(code)(); 
  45.  
  46.  // 返回 render 方法的同時,將其放入緩存 
  47.   return (compileCache[key] = render) 
  48.  
  49. // 注入 compile 
  50. registerRuntimeCompiler(compileToFunction) 

在講 Vue2 模板編譯的時候已經(jīng)講過,compile 方法主要分為三步,Vue3 的邏輯類似:

  1. 模板編譯,將模板代碼轉(zhuǎn)化為 AST;
  2. 優(yōu)化 AST,方便后續(xù)虛擬 DOM 更新;
  3. 生成代碼,將 AST 轉(zhuǎn)化為可執(zhí)行的代碼;
  1. // packages/compiler-dom/src/index.ts 
  2. import { baseCompile, baseParse } from '@vue/compiler-core' 
  3. export function compile(template, options) { 
  4.   return baseCompile(template, options) 
  5.  
  6. // packages/compiler-core/src/compile.ts 
  7. import { baseParse } from './parse' 
  8. import { transform } from './transform' 
  9.  
  10. import { transformIf } from './transforms/vIf' 
  11. import { transformFor } from './transforms/vFor' 
  12. import { transformText } from './transforms/transformText' 
  13. import { transformElement } from './transforms/transformElement' 
  14.  
  15. import { transformOn } from './transforms/vOn' 
  16. import { transformBind } from './transforms/vBind' 
  17. import { transformModel } from './transforms/vModel' 
  18.  
  19. export function baseCompile(template, options) { 
  20.   // 解析 html,轉(zhuǎn)化為 ast 
  21.   const ast = baseParse(template, options) 
  22.   // 優(yōu)化 ast,標記靜態(tài)節(jié)點 
  23.   transform(ast, { 
  24.     ...options, 
  25.     nodeTransforms: [ 
  26.       transformIf, 
  27.       transformFor, 
  28.       transformText, 
  29.       transformElement, 
  30.       // ... 省略了部分 transform 
  31.     ], 
  32.     directiveTransforms: { 
  33.       on: transformOn, 
  34.       bind: transformBind, 
  35.       model: transformModel 
  36.     } 
  37.   }) 
  38.   // 將 ast 轉(zhuǎn)化為可執(zhí)行代碼 
  39.   return generate(ast, options) 

計算 PatchFlag

這里大致的邏輯與之前的并沒有多大的差異,主要是 optimize 方法變成了 transform 方法,而且默認會對一些模板語法進行 transform。這些 transform 就是后續(xù)虛擬 DOM 優(yōu)化的關(guān)鍵,我們先看看 transform 的代碼 。

  1. // packages/compiler-core/src/transform.ts 
  2. export function transform(root, options) { 
  3.   const context = createTransformContext(root, options) 
  4.   traverseNode(root, context) 
  5. export function traverseNode(node, context) { 
  6.   context.currentNode = node 
  7.   const { nodeTransforms } = context 
  8.   const exitFns = [] 
  9.   for (let i = 0; i < nodeTransforms.length; i++) { 
  10.     // Transform 會返回一個退出函數(shù),在處理完所有的子節(jié)點后再執(zhí)行 
  11.     const onExit = nodeTransforms[i](node, context) 
  12.     if (onExit) { 
  13.       if (isArray(onExit)) { 
  14.         exitFns.push(...onExit) 
  15.       } else { 
  16.         exitFns.push(onExit) 
  17.       } 
  18.     } 
  19.   } 
  20.   traverseChildren(node, context) 
  21.   context.currentNode = node 
  22.   // 執(zhí)行所以 Transform 的退出函數(shù) 
  23.   let i = exitFns.length 
  24.   while (i--) { 
  25.     exitFns[i]() 
  26.   } 

我們重點看一下 transformElement 的邏輯:

  1. // packages/compiler-core/src/transforms/transformElement.ts 
  2. export const transformElement: NodeTransform = (node, context) => { 
  3.   // transformElement 沒有執(zhí)行任何邏輯,而是直接返回了一個退出函數(shù) 
  4.   // 說明 transformElement 需要等所有的子節(jié)點處理完后才執(zhí)行 
  5.   return function postTransformElement() { 
  6.     const { tag, props } = node 
  7.  
  8.     let vnodeProps 
  9.     let vnodePatchFlag 
  10.     const vnodeTag = node.tagType === ElementTypes.COMPONENT 
  11.       ? resolveComponentType(node, context) 
  12.       : `"${tag}"
  13.      
  14.     let patchFlag = 0 
  15.     // 檢測節(jié)點屬性 
  16.     if (props.length > 0) { 
  17.       // 檢測節(jié)點屬性的動態(tài)部分 
  18.       const propsBuildResult = buildProps(node, context) 
  19.       vnodeProps = propsBuildResult.props 
  20.       patchFlag = propsBuildResult.patchFlag 
  21.     } 
  22.  
  23.     // 檢測子節(jié)點 
  24.     if (node.children.length > 0) { 
  25.       if (node.children.length === 1) { 
  26.         const child = node.children[0] 
  27.         // 檢測子節(jié)點是否為動態(tài)文本 
  28.         if (!getStaticType(child)) { 
  29.           patchFlag |= PatchFlags.TEXT 
  30.         } 
  31.       } 
  32.     } 
  33.  
  34.     // 格式化 patchFlag 
  35.     if (patchFlag !== 0) { 
  36.         vnodePatchFlag = String(patchFlag) 
  37.     } 
  38.  
  39.     node.codegenNode = createVNodeCall( 
  40.       context, 
  41.       vnodeTag, 
  42.       vnodeProps, 
  43.       vnodeChildren, 
  44.       vnodePatchFlag 
  45.     ) 
  46.   } 

buildProps 會對節(jié)點的屬性進行一次遍歷,由于內(nèi)部源碼涉及很多其他的細節(jié),這里的代碼是經(jīng)過簡化之后的,只保留了 patchFlag 相關(guān)的邏輯。

  1. export function buildProps( 
  2.   node: ElementNode, 
  3.   context: TransformContext, 
  4.   props: ElementNode['props'] = node.props 
  5. ) { 
  6.   let patchFlag = 0 
  7.   for (let i = 0; i < props.length; i++) { 
  8.     const prop = props[i] 
  9.     const [keyname] = prop.name.split(':'
  10.     if (key === 'v-bind' || key === '') { 
  11.       if (name === 'class') { 
  12.        // 如果包含 :class 屬性,patchFlag | CLASS 
  13.         patchFlag |= PatchFlags.CLASS 
  14.       } else if (name === 'style') { 
  15.        // 如果包含 :style 屬性,patchFlag | STYLE 
  16.         patchFlag |= PatchFlags.STYLE 
  17.       } 
  18.     } 
  19.   } 
  20.  
  21.   return { 
  22.     patchFlag 
  23.   } 

上面的代碼只展示了三種 patchFlag 的類型:

  • 節(jié)點只有一個文本子節(jié)點,且該文本包含動態(tài)的數(shù)據(jù)(TEXT = 1)
  1. <p>name: {{name}}</p> 
  • 節(jié)點包含可變的 class 屬性(CLASS = 1 << 1)
    1. <div :class="{ active: isActive }"></div> 

節(jié)點包含可變的 style 屬性(STYLE = 1 << 2)

  1. <div :style="{ color: color }"></div> 

可以看到 PatchFlags 都是數(shù)字 1 經(jīng)過 左移操作符 計算得到的。

  1. export const enum PatchFlags { 
  2.   TEXT = 1,             // 1, 二進制 0000 0001 
  3.   CLASS = 1 << 1,       // 2, 二進制 0000 0010 
  4.   STYLE = 1 << 2,       // 4, 二進制 0000 0100 
  5.   PROPS = 1 << 3,       // 8, 二進制 0000 1000 
  6.   ... 

從上面的代碼能看出來,patchFlag 的初始值為 0,每次對 patchFlag 都是執(zhí)行 | (或)操作。如果當(dāng)前節(jié)點是一個只有動態(tài)文本子節(jié)點且同時具有動態(tài) style 屬性,最后得到的 patchFlag 為 5(二進制:0000 0101)。

  1. <p :style="{ color: color }">name: {{name}}</p> 

我們將上面的代碼放到 Vue3 中運行:

  1. const app = Vue.createApp({ 
  2.   data() { 
  3.     return { 
  4.       color: 'red'
  5.       name'shenfq' 
  6.     } 
  7.   }, 
  8.   template: `<div> 
  9.    <p :style="{ color: color }">name: {{name}}</p> 
  10.   </div>` 
  11. }) 
  12.  
  13. app.mount('#app'

最后生成的 render 方法如下,和我們之前的描述基本一致。

function render() {}

render 優(yōu)化

Vue3 在虛擬 DOM Diff 時,會取出 patchFlag 和需要進行的 diff 類型進行 &(與)操作,如果結(jié)果為 true 才進入對應(yīng)的 diff。

patchFlag 判斷

還是拿之前的模板舉例:

  1. <p :style="{ color: color }">name: {{name}}</p> 

如果此時的 name 發(fā)生了修改,p 節(jié)點進入了 diff 階段,此時會將判斷 patchFlag & PatchFlags.TEXT ,這個時候結(jié)果為真,表明 p 節(jié)點存在文本修改的情況。

patchFlag

  1. patchFlag = 5 
  2. patchFlag & PatchFlags.TEXT 
  3. // 或運算:只有對應(yīng)的兩個二進位都為1時,結(jié)果位才為1。 
  4. // 0000 0101 
  5. // 0000 0001 
  6. // ------------ 
  7. // 0000 0001  =>  十進制 1 
  1. if (patchFlag & PatchFlags.TEXT) { 
  2.   if (oldNode.children !== newNode.children) { 
  3.     // 修改文本 
  4.     hostSetElementText(el, newNode.children) 
  5.   } 

但是進行 patchFlag & PatchFlags.CLASS 判斷時,由于節(jié)點并沒有動態(tài) Class,返回值為 0,所以就不會對該節(jié)點的 class 屬性進行 diff,以此來優(yōu)化性能。

patchFlag

  1. patchFlag = 5 
  2. patchFlag & PatchFlags.CLASS 
  3. // 或運算:只有對應(yīng)的兩個二進位都為1時,結(jié)果位才為1。 
  4. // 0000 0101 
  5. // 0000 0010 
  6. // ------------ 
  7. // 0000 0000  =>  十進制 0 

總結(jié)

其實 Vue3 相關(guān)的性能優(yōu)化有很多,這里只單獨將 patchFlag 的十分之一的內(nèi)容拿出來講了,Vue3 還沒正式發(fā)布的時候就有看到說 Diff 過程會通過 patchFlag 來進行性能優(yōu)化,所以打算看看他的優(yōu)化邏輯,總的來說還是有所收獲。

本文轉(zhuǎn)載自微信公眾號「更了不起的前端」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系更了不起的前端公眾號。

 

責(zé)任編輯:武曉燕 來源: 更了不起的前端
相關(guān)推薦

2021-01-15 05:16:37

Vue3開源代碼量

2021-12-01 08:11:44

Vue3 插件Vue應(yīng)用

2020-09-14 08:56:30

Vue模板

2021-11-30 08:19:43

Vue3 插件Vue應(yīng)用

2023-11-28 09:03:59

Vue.jsJavaScript

2021-12-02 05:50:35

Vue3 插件Vue應(yīng)用

2020-09-19 21:15:26

Composition

2024-07-26 08:50:57

2021-12-08 09:09:33

Vue 3 Computed Vue2

2021-05-12 08:57:56

項目搭建工具

2022-06-21 12:09:18

Vue差異

2025-01-20 00:00:06

Vue開發(fā)工具庫

2021-05-26 10:40:28

Vue3TypeScript前端

2021-11-16 08:50:29

Vue3 插件Vue應(yīng)用

2022-03-10 11:04:04

Vue3Canvas前端

2020-12-01 08:34:31

Vue3組件實踐

2024-11-06 10:16:22

2024-02-28 08:35:26

內(nèi)置組件Vue3頁面

2023-04-28 08:35:22

Vue 3Vue 2

2021-09-26 00:24:58

開發(fā)項目TypeScript
點贊
收藏

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