成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

聊聊Vue3 的模板編譯優化

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

[[351771]]

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

編譯入口

了解過 Vue3 的同學肯定知道 Vue3 引入了新的組合 Api,在組件 mount 階段會調用 setup 方法,之后會判斷 render 方法是否存在,如果不存在會調用 compile 方法將 template 轉化為 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.   // 調用 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.     // ...調用 setup 
  20.   } 
  21.   if (compile && Component.template && !Component.render) { 
  22.    // 如果沒有 render 方法 
  23.     // 調用 compile 將 template 轉為 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 過程都放到打包的階段,以此優化性能。runtime-dom 中提供了 registerRuntimeCompiler 方法用于注入 compile 方法。

主流程

在完整版的 index.js 中,調用了 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 節點,獲取 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.   // 調用 compile 獲取 render code 
  38.   const { code } = compile( 
  39.     template, 
  40.     options 
  41.   ) 
  42.  
  43.   // 將 render code 轉化為 function 
  44.   const render = new Function(code)(); 
  45.  
  46.  // 返回 render 方法的同時,將其放入緩存 
  47.   return (compileCache[key] = render) 
  48.  
  49. // 注入 compile 
  50. registerRuntimeCompiler(compileToFunction) 

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

  1. 模板編譯,將模板代碼轉化為 AST;
  2. 優化 AST,方便后續虛擬 DOM 更新;
  3. 生成代碼,將 AST 轉化為可執行的代碼;
  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,轉化為 ast 
  21.   const ast = baseParse(template, options) 
  22.   // 優化 ast,標記靜態節點 
  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 轉化為可執行代碼 
  39.   return generate(ast, options) 

計算 PatchFlag

這里大致的邏輯與之前的并沒有多大的差異,主要是 optimize 方法變成了 transform 方法,而且默認會對一些模板語法進行 transform。這些 transform 就是后續虛擬 DOM 優化的關鍵,我們先看看 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 會返回一個退出函數,在處理完所有的子節點后再執行 
  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.   // 執行所以 Transform 的退出函數 
  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 沒有執行任何邏輯,而是直接返回了一個退出函數 
  4.   // 說明 transformElement 需要等所有的子節點處理完后才執行 
  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.     // 檢測節點屬性 
  16.     if (props.length > 0) { 
  17.       // 檢測節點屬性的動態部分 
  18.       const propsBuildResult = buildProps(node, context) 
  19.       vnodeProps = propsBuildResult.props 
  20.       patchFlag = propsBuildResult.patchFlag 
  21.     } 
  22.  
  23.     // 檢測子節點 
  24.     if (node.children.length > 0) { 
  25.       if (node.children.length === 1) { 
  26.         const child = node.children[0] 
  27.         // 檢測子節點是否為動態文本 
  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 會對節點的屬性進行一次遍歷,由于內部源碼涉及很多其他的細節,這里的代碼是經過簡化之后的,只保留了 patchFlag 相關的邏輯。

  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 的類型:

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

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

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

可以看到 PatchFlags 都是數字 1 經過 左移操作符 計算得到的。

  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 都是執行 | (或)操作。如果當前節點是一個只有動態文本子節點且同時具有動態 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 優化

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

patchFlag 判斷

還是拿之前的模板舉例:

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

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

patchFlag

  1. patchFlag = 5 
  2. patchFlag & PatchFlags.TEXT 
  3. // 或運算:只有對應的兩個二進位都為1時,結果位才為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 判斷時,由于節點并沒有動態 Class,返回值為 0,所以就不會對該節點的 class 屬性進行 diff,以此來優化性能。

patchFlag

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

總結

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

本文轉載自微信公眾號「更了不起的前端」,可以通過以下二維碼關注。轉載本文請聯系更了不起的前端公眾號。

 

責任編輯:武曉燕 來源: 更了不起的前端
相關推薦

2021-01-15 05:16:37

Vue3開源代碼量

2021-12-01 08:11:44

Vue3 插件Vue應用

2020-09-14 08:56:30

Vue模板

2021-11-30 08:19:43

Vue3 插件Vue應用

2023-11-28 09:03:59

Vue.jsJavaScript

2021-12-02 05:50:35

Vue3 插件Vue應用

2024-07-26 08:50:57

2020-09-19 21:15:26

Composition

2021-05-12 08:57:56

項目搭建工具

2021-12-08 09:09:33

Vue 3 Computed Vue2

2025-01-20 00:00:06

Vue開發工具庫

2025-05-06 09:35:00

2022-06-21 12:09:18

Vue差異

2021-11-16 08:50:29

Vue3 插件Vue應用

2021-05-26 10:40:28

Vue3TypeScript前端

2022-03-10 11:04:04

Vue3Canvas前端

2021-01-14 08:58:12

Synchronize鎖操作

2020-12-01 08:34:31

Vue3組件實踐

2024-11-06 10:16:22

2024-02-28 08:35:26

內置組件Vue3頁面
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 天天综合亚洲 | 一区二区三区在线免费 | 欧美日韩在线免费观看 | 中文字幕亚洲免费 | 伊人超碰 | 国产精品a久久久久 | 麻豆av电影网 | 国内精品99 | 亚洲欧美在线一区 | 日本精品视频在线观看 | 免费观看av | 日韩91 | 久久性av| 欧美精品网| 国产日韩欧美91 | 国产精品亚洲二区 | 一区二视频| 亚洲第一网站 | 日韩视频―中文字幕 | 精品久久久久久久久久久院品网 | 久久久久久久久久久久久9999 | 日韩一三区| 成人精品一区二区 | 国产91丝袜在线播放 | 欧美激情久久久 | 亚洲一区av| 日韩在线观看一区 | 成人小视频在线 | 亚洲激情在线视频 | 国产区精品| 自拍偷拍第一页 | 久久久www| 国产精品国产a级 | 欧美日韩国产传媒 | 欧美亚洲国产一区二区三区 | 久久91精品国产一区二区三区 | 天天操网 | 日韩欧美中文字幕在线观看 | 国产一区二区在线免费播放 | 久久久久久成人 | 国产高清精品一区二区三区 |