Vue.js 3.0 核心源码解析 - 前百度、滴滴资深技术专家 - 拉勾教育

上节课,我们已经知道了在 AST 转换后,会执行 generate 函数生成代码,而 generate 主要做五件事情:创建代码生成上下文,生成预设代码,生成渲染函数,生成资源声明代码,以及生成创建 VNode 树的表达式。这节课我们继续分析,来看生成创建 VNode 树的表达式的过程。

生成创建 VNode 树的表达式

我们先来看它的实现:

  1. if (ast.codegenNode) {
  2. genNode(ast.codegenNode, context);
  3. }
  4. else {
  5. push(`null`);
  6. }

前面我们在转换过程中给根节点添加了 codegenNode,所以接下来就是通过 genNode 生成创建 VNode 树的表达式,我们来看它的实现:

  1. function genNode(node, context) {
  2. if (shared.isString(node)) {
  3. context.push(node)
  4. return
  5. }
  6. if (shared.isSymbol(node)) {
  7. context.push(context.helper(node))
  8. return
  9. }
  10. switch (node.type) {
  11. case 1 :
  12. case 9 :
  13. case 11 :
  14. genNode(node.codegenNode, context)
  15. break
  16. case 2 :
  17. genText(node, context)
  18. break
  19. case 4 :
  20. genExpression(node, context)
  21. break
  22. case 5 :
  23. genInterpolation(node, context)
  24. break
  25. case 12 :
  26. genNode(node.codegenNode, context)
  27. break
  28. case 8 :
  29. genCompoundExpression(node, context)
  30. break
  31. case 3 :
  32. break
  33. case 13 :
  34. genVNodeCall(node, context)
  35. break
  36. case 14 :
  37. genCallExpression(node, context)
  38. break
  39. case 15 :
  40. genObjectExpression(node, context)
  41. break
  42. case 17 :
  43. genArrayExpression(node, context)
  44. break
  45. case 18 :
  46. genFunctionExpression(node, context)
  47. break
  48. case 19 :
  49. genConditionalExpression(node, context)
  50. break
  51. case 20 :
  52. genCacheExpression(node, context)
  53. break
  54. case 21 :
  55. genNodeList(node.body, context, true, false)
  56. break
  57. case 22 :
  58. genTemplateLiteral(node, context)
  59. break
  60. case 23 :
  61. genIfStatement(node, context)
  62. break
  63. case 24 :
  64. genAssignmentExpression(node, context)
  65. break
  66. case 25 :
  67. genSequenceExpression(node, context)
  68. break
  69. case 26 :
  70. genReturnStatement(node, context)
  71. break
  72. }
  73. }

genNode 主要的思路就是根据不同的节点类型,生成不同的代码,这里有十几种情况,我就不全部讲一遍了,仍然是以我们的示例为主,来分析它们的实现,没有分析到的分支我的建议是大致了解即可,未来如果遇到相关的场景,你再来详细看它们的实现也不迟。

现在,我们来看一下根节点 codegenNode 的值:

  1. {
  2. type: 13,
  3. tag: "div",
  4. children: [
  5. ],
  6. props: {
  7. },
  8. directives: undefined,
  9. disableTracking: false,
  10. dynamicProps: undefined,
  11. isBlock: true,
  12. patchFlag: undefined
  13. }

由于根节点的 codegenNode 类型是 13,也就是一个 VNodeCall,所以会执行 genVNodeCall 生成创建 VNode 节点的表达式代码,它的实现如下 :

  1. function genVNodeCall(node, context) {
  2. const { push, helper, pure } = context
  3. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking } = node
  4. if (directives) {
  5. push(helper(WITH_DIRECTIVES) + `(`)
  6. }
  7. if (isBlock) {
  8. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `)
  9. }
  10. if (pure) {
  11. push(PURE_ANNOTATION)
  12. }
  13. push(helper(isBlock ? CREATE_BLOCK : CREATE_VNODE) + `(`, node)
  14. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context)
  15. push(`)`)
  16. if (isBlock) {
  17. push(`)`)
  18. }
  19. if (directives) {
  20. push(`, `)
  21. genNode(directives, context)
  22. push(`)`)
  23. }
  24. }

根据我们的示例来看,directives 没定义,不用处理,isBlock 为 true,disableTracking 为 false,那么生成如下打开 Block 的代码:

  1. import { resolveComponent as _resolveComponent, createVNode as _createVNode, createCommentVNode as _createCommentVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createBlock as _createBlock } from "vue"
  2. const _hoisted_1 = { class: "app" }
  3. const _hoisted_2 = { key: 1 }
  4. const _hoisted_3 = _createVNode("p", null, "static", -1 )
  5. const _hoisted_4 = _createVNode("p", null, "static", -1 )
  6. export function render(_ctx, _cache) {
  7. const _component_hello = _resolveComponent("hello")
  8. return (_openBlock()

接着往下看,会判断 pure 是否为 true,如果是则生成相关的注释,虽然这里的 pure 为 false,但是之前我们在生成静态提升变量相关代码的时候 pure 为 true,所以生成了注释代码 /#PURE**/。

接下来会判断 isBlock,如果它为 true 则在生成创建 Block 相关代码,如果它为 false,则生成创建 VNode 的相关代码。

因为这里 isBlock 为 true,所以生成如下代码:

  1. import { resolveComponent as _resolveComponent, createVNode as _createVNode, createCommentVNode as _createCommentVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createBlock as _createBlock } from "vue"
  2. const _hoisted_1 = { class: "app" }
  3. const _hoisted_2 = { key: 1 }
  4. const _hoisted_3 = _createVNode("p", null, "static", -1 )
  5. const _hoisted_4 = _createVNode("p", null, "static", -1 )
  6. export function render(_ctx, _cache) {
  7. const _component_hello = _resolveComponent("hello")
  8. return (_openBlock(), _createBlock(

生成了一个_createBlock 的函数调用后,下面就需要生成函数的参数,通过如下代码生成:

  1. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context)

依据代码的执行顺序,我们先来看 genNullableArgs 的实现:

  1. function genNullableArgs(args) {
  2. let i = args.length
  3. while (i--) {
  4. if (args[i] != null)
  5. break
  6. }
  7. return args.slice(0, i + 1).map(arg => arg || `null`)
  8. }

这个方法很简单,就是倒序遍历参数数组,找到第一个不为空的参数,然后返回该参数前面的所有参数构成的新数组。

genNullableArgs 传入的参数数组依次是 tag、props、children、patchFlag 和 dynamicProps,对于我们的示例而言,此时 patchFlag 和 dynamicProps 为 undefined,所以 genNullableArgs 返回的是一个[tag, props, children]这样的数组。

其实这是很好理解的,对于一个 vnode 节点而言,构成它的主要几个部分就是节点的标签 tag,属性 props 以及子节点 children,我们的目标就是生成类似下面的代码:_createBlock(tag, props, children)

因此接下来,我们再通过 genNodeList 来生成参数相关的代码,来看一下它的实现:

  1. function genNodeList(nodes, context, multilines = false, comma = true) {
  2. const { push, newline } = context
  3. for (let i = 0; i < nodes.length; i++) {
  4. const node = nodes[i]
  5. if (shared.isString(node)) {
  6. push(node)
  7. }
  8. else if (shared.isArray(node)) {
  9. genNodeListAsArray(node, context)
  10. }
  11. else {
  12. genNode(node, context)
  13. }
  14. if (i < nodes.length - 1) {
  15. if (multilines) {
  16. comma && push(',')
  17. newline()
  18. }
  19. else {
  20. comma && push(', ')
  21. }
  22. }
  23. }
  24. }

genNodeList 就是通过遍历 nodes,拿到每一个 node,然后判断 node 的类型,如果 node 是字符串,就直接添加到代码中;如果是一个数组,则执行 genNodeListAsArray 生成数组形式的代码,否则是一个对象,则递归执行 genNode 生成节点代码。

我们还是根据示例代码走完这个流程,此时 nodes 的值如下:

  1. ['div', {
  2. type: 4,
  3. content: '_hoisted_1',
  4. isConstant: true,
  5. isStatic: false,
  6. hoisted: {
  7. },
  8. },
  9. [
  10. {
  11. type: 9,
  12. branches: [
  13. ],
  14. codegenNode: {
  15. }
  16. }
  17. ]
  18. ]

接下来我们依据 nodes 的值继续生成代码,首先 nodes 第一个元素的值是’div’ 字符串,根据前面的逻辑,直接把字符串添加到代码上即可,由于 multilines 为 false,comma 为 true,因此生成如下代码:

  1. import { resolveComponent as _resolveComponent, createVNode as _createVNode, createCommentVNode as _createCommentVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createBlock as _createBlock } from "vue"
  2. const _hoisted_1 = { class: "app" }
  3. const _hoisted_2 = { key: 1 }
  4. const _hoisted_3 = _createVNode("p", null, "static", -1 )
  5. const _hoisted_4 = _createVNode("p", null, "static", -1 )
  6. export function render(_ctx, _cache) {
  7. const _component_hello = _resolveComponent("hello")
  8. return (_openBlock(), _createBlock("div",

接下来看 nodes 第二个元素,它代表的是 vnode 的属性 props,是一个简单的对象表达式,就会递归执行 genNode,进一步执行 genExpression,来看一下它的实现:

  1. function genExpression(node, context) {
  2. const { content, isStatic } = node
  3. context.push(isStatic ? JSON.stringify(content) : content, node)
  4. }

这里 genExpression 非常简单,就是往代码中添加 content 的内容。此时 node 中的 content 值是 _hoisted_1,再回到 genNodeList,由于 multilines 为 false,comma 为 true,因此生成如下代码:

  1. import { resolveComponent as _resolveComponent, createVNode as _createVNode, createCommentVNode as _createCommentVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createBlock as _createBlock } from "vue"
  2. const _hoisted_1 = { class: "app" }
  3. const _hoisted_2 = { key: 1 }
  4. const _hoisted_3 = _createVNode("p", null, "static", -1 )
  5. const _hoisted_4 = _createVNode("p", null, "static", -1 )
  6. export function render(_ctx, _cache) {
  7. const _component_hello = _resolveComponent("hello")
  8. return (_openBlock(), _createBlock("div", _hoisted_1,

接下来我们再看 nodes 第三个元素,它代表的是子节点 chidren,是一个数组,那么会执行 genNodeListAsArray,来看它的实现:

  1. function genNodeListAsArray(nodes, context) {
  2. const multilines = nodes.length > 3 || nodes.some(n => isArray(n) || !isText$1(n))
  3. context.push(`[`)
  4. multilines && context.indent()
  5. genNodeList(nodes, context, multilines);
  6. multilines && context.deindent()
  7. context.push(`]`)
  8. }

genNodeListAsArray 主要是把一个 node 列表生成一个类似数组形式的代码,所以前后会添加中括号,并且判断是否要生成多行代码,如果是多行,前后还需要加减代码的缩进,而中间部分的代码,则继续递归调用 genNodeList 生成。

那么针对我们的示例,此时参数 nodes 的值如下:

  1. [
  2. {
  3. type: 9,
  4. branches: [
  5. ],
  6. codegenNode: {
  7. }
  8. }
  9. ]

它是一个长度为 1 的数组,但是这个数组元素的类型是一个对象,所以 multilines 为 true。那么在执行 genNodeList 之前,生成的代码是这样的:

  1. import { resolveComponent as _resolveComponent, createVNode as _createVNode, createCommentVNode as _createCommentVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createBlock as _createBlock } from "vue"
  2. const _hoisted_1 = { class: "app" }
  3. const _hoisted_2 = { key: 1 }
  4. const _hoisted_3 = _createVNode("p", null, "static", -1 )
  5. const _hoisted_4 = _createVNode("p", null, "static", -1 )
  6. export function render(_ctx, _cache) {
  7. const _component_hello = _resolveComponent("hello")
  8. return (_openBlock(), _createBlock("div", _hoisted_1, [

接下来就是递归执行 genNodeList 的过程,由于 nodes 数组只有一个对象类型的元素,则执行 genNode,并且这个对象的类型是 IF 表达式,回顾 genNode 的实现,此时会执行到genNode(node.codegenNode, context),也就是取节点的 codegenNode,进一步执行 genNode,我们来看一下这个 codegenNode:

  1. {
  2. type: 19,
  3. consequent: {
  4. type: 13,
  5. tag: "_component_hello",
  6. children: undefined,
  7. props: {
  8. },
  9. directives: undefined,
  10. disableTracking: false,
  11. dynamicProps: undefined,
  12. isBlock: false,
  13. patchFlag: undefined
  14. },
  15. alternate: {
  16. type: 13,
  17. tag: "div",
  18. children: [
  19. ],
  20. props: {
  21. },
  22. directives: undefined,
  23. disableTracking: false,
  24. dynamicProps: undefined,
  25. isBlock: true,
  26. patchFlag: undefined
  27. },
  28. test: {
  29. type: 4,
  30. content: "_ctx.flag",
  31. isConstant: false,
  32. isStatic: false
  33. },
  34. newline: true
  35. }

它是一个条件表达式节点,它主要包括 3 个重要的属性,其中 test 表示逻辑测试,它是一个表达式节点,consequent 表示主逻辑,它是一个 vnode 调用节点,alternate 表示备选逻辑,它也是一个 vnode 调用节点。

其实条件表达式节点要生成代码就是一个条件表达式,用伪代码表示是:test ? consequent : alternate

genNode 遇到条件表达式节点会执行 genConditionalExpression,我们来看一下它的实现:

  1. function genConditionalExpression(node, context) {
  2. const { test, consequent, alternate, newline: needNewline } = node
  3. const { push, indent, deindent, newline } = context
  4. if (test.type === 4 ) {
  5. const needsParens = !isSimpleIdentifier(test.content)
  6. needsParens && push(`(`)
  7. genExpression(test, context)
  8. needsParens && push(`)`)
  9. }
  10. else {
  11. push(`(`)
  12. genNode(test, context)
  13. push(`)`)
  14. }
  15. needNewline && indent()
  16. context.indentLevel++
  17. needNewline || push(` `)
  18. push(`? `)
  19. genNode(consequent, context)
  20. context.indentLevel--
  21. needNewline && newline()
  22. needNewline || push(` `)
  23. push(`: `)
  24. const isNested = alternate.type === 19
  25. if (!isNested) {
  26. context.indentLevel++
  27. }
  28. genNode(alternate, context)
  29. if (!isNested) {
  30. context.indentLevel--
  31. }
  32. needNewline && deindent(true )
  33. }

genConditionalExpression 的主要目的就是生成条件表达式代码,所以首先它会生成逻辑测试的代码。对于示例,我们这里是一个简单表达式节点,所以生成的代码是这样的:

  1. import { resolveComponent as _resolveComponent, createVNode as _createVNode, createCommentVNode as _createCommentVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createBlock as _createBlock } from "vue"
  2. const _hoisted_1 = { class: "app" }
  3. const _hoisted_2 = { key: 1 }
  4. const _hoisted_3 = _createVNode("p", null, "static", -1 )
  5. const _hoisted_4 = _createVNode("p", null, "static", -1 )
  6. export function render(_ctx, _cache) {
  7. const _component_hello = _resolveComponent("hello")
  8. return (_openBlock(), _createBlock("div", _hoisted_1, [
  9. (_ctx.flag)

接下来就是生成一些换行和缩进,紧接着生成主逻辑代码,也就是把 consequent 这个 vnode 调用节点通过 genNode 转换生成代码,这又是一个递归过程,其中的细节我就不再赘述了,执行完后会生成如下代码:

  1. import { resolveComponent as _resolveComponent, createVNode as _createVNode, createCommentVNode as _createCommentVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createBlock as _createBlock } from "vue"
  2. const _hoisted_1 = { class: "app" }
  3. const _hoisted_2 = { key: 1 }
  4. const _hoisted_3 = _createVNode("p", null, "static", -1 )
  5. const _hoisted_4 = _createVNode("p", null, "static", -1 )
  6. export function render(_ctx, _cache) {
  7. const _component_hello = _resolveComponent("hello")
  8. return (_openBlock(), _createBlock("div", _hoisted_1, [
  9. (_ctx.flag)
  10. ? _createVNode(_component_hello, { key: 0 })

接下来就是生成备选逻辑的代码,即把 alternate 这个 vnode 调用节点通过 genNode 转换生成代码,同样内部的细节我就不赘述了,感兴趣同学可以自行调试。

需要注意的是,alternate 对应的节点的 isBlock 属性是 true所以会生成创建 Block 相关的代码,最终生成的代码如下:

  1. import { resolveComponent as _resolveComponent, createVNode as _createVNode, createCommentVNode as _createCommentVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createBlock as _createBlock } from "vue"
  2. const _hoisted_1 = { class: "app" }
  3. const _hoisted_2 = { key: 1 }
  4. const _hoisted_3 = _createVNode("p", null, "static", -1 )
  5. const _hoisted_4 = _createVNode("p", null, "static", -1 )
  6. export function render(_ctx, _cache) {
  7. const _component_hello = _resolveComponent("hello")
  8. return (_openBlock(), _createBlock("div", _hoisted_1, [
  9. (_ctx.flag)
  10. ? _createVNode(_component_hello, { key: 0 })
  11. : (_openBlock(), _createBlock("div", _hoisted_2, [
  12. _createVNode("p", null, ">hello " + _toDisplayString(_ctx.msg + _ctx.test), 1 ),
  13. _hoisted_3,
  14. _hoisted_4
  15. ]))

接下来我们回到 genNodeListAsArray 函数,处理完 children,那么下面就会减少缩进,并添加闭合的中括号,就会生成如下的代码:

  1. import { resolveComponent as _resolveComponent, createVNode as _createVNode, createCommentVNode as _createCommentVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createBlock as _createBlock } from "vue"
  2. const _hoisted_1 = { class: "app" }
  3. const _hoisted_2 = { key: 1 }
  4. const _hoisted_3 = _createVNode("p", null, "static", -1 )
  5. const _hoisted_4 = _createVNode("p", null, "static", -1 )
  6. export function render(_ctx, _cache) {
  7. const _component_hello = _resolveComponent("hello")
  8. return (_openBlock(), _createBlock("div", _hoisted_1, [
  9. (_ctx.flag)
  10. ? _createVNode(_component_hello, { key: 0 })
  11. : (_openBlock(), _createBlock("div", _hoisted_2, [
  12. _createVNode("p", null, ">hello " + _toDisplayString(_ctx.msg + _ctx.test), 1 ),
  13. _hoisted_3,
  14. _hoisted_4
  15. ]))
  16. ]

genNodeListAsArray 处理完子节点后,回到 genNodeList,发现所有 nodes 也处理完了,则回到 genVNodeCall 函数,接下来的逻辑就是补齐函数调用的右括号,此时生成的代码是这样的:

  1. import { resolveComponent as _resolveComponent, createVNode as _createVNode, createCommentVNode as _createCommentVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createBlock as _createBlock } from "vue"
  2. const _hoisted_1 = { class: "app" }
  3. const _hoisted_2 = { key: 1 }
  4. const _hoisted_3 = _createVNode("p", null, "static", -1 )
  5. const _hoisted_4 = _createVNode("p", null, "static", -1 )
  6. export function render(_ctx, _cache) {
  7. const _component_hello = _resolveComponent("hello")
  8. return (_openBlock(), _createBlock("div", _hoisted_1, [
  9. (_ctx.flag)
  10. ? _createVNode(_component_hello, { key: 0 })
  11. : (_openBlock(), _createBlock("div", _hoisted_2, [
  12. _createVNode("p", null, ">hello " + _toDisplayString(_ctx.msg + _ctx.test), 1 ),
  13. _hoisted_3,
  14. _hoisted_4
  15. ]))
  16. ]))

那么至此,根节点 vnode 树的表达式就创建好了。我们再回到 generate 函数,接下来就需要添加右括号 “}” 来闭合渲染函数,最终生成如下代码:

  1. import { resolveComponent as _resolveComponent, createVNode as _createVNode, createCommentVNode as _createCommentVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createBlock as _createBlock } from "vue"
  2. const _hoisted_1 = { class: "app" }
  3. const _hoisted_2 = { key: 1 }
  4. const _hoisted_3 = _createVNode("p", null, "static", -1 )
  5. const _hoisted_4 = _createVNode("p", null, "static", -1 )
  6. export function render(_ctx, _cache) {
  7. const _component_hello = _resolveComponent("hello")
  8. return (_openBlock(), _createBlock("div", _hoisted_1, [
  9. (_ctx.flag)
  10. ? _createVNode(_component_hello, { key: 0 })
  11. : (_openBlock(), _createBlock("div", _hoisted_2, [
  12. _createVNode("p", null, "hello " + _toDisplayString(_ctx.msg + _ctx.test), 1 ),
  13. _hoisted_3,
  14. _hoisted_4
  15. ]))
  16. ]))
  17. }

这就是示例 template 编译生成的最终代码,虽然我们忽略了其中子节点的一些实现细节,但是整体流程还是很容易理解的,主要就是一个递归的思想,遇到不同类型的节点,执行相应的代码生成函数生成代码即可。

节点生成代码的所需的信息可以从节点的属性中获取,这完全得益于前面 transform 的语法分析阶段生成的 codegenNode,根据这些信息就能很容易地生成对应的代码了。

至此,我们已经了解了模板的编译到代码的全部流程。相比 Vue.js 2.x,Vue.js 3.0 在编译阶段设计了 Block 的概念,我们上述示例编译出来的代码就是通过创建一个 Block 来创建对应的 vnode。

那么,这个 Block 在运行时是怎么玩的呢?为什么它会对性能优化起到很大的作用呢?接下来我们就来分析它背后的实现原理。

运行时优化

首先,我们来看一下 openBlock 的实现:

  1. const blockStack = []
  2. let currentBlock = null
  3. function openBlock(disableTracking = false) {
  4. blockStack.push((currentBlock = disableTracking ? null : []));
  5. }

Vue.js 3.0 在运行时设计了一个 blockStack 和 currentBlock,其中 blockStack 表示一个 Block Tree,因为要考虑嵌套 Block 的情况,而 currentBlock 表示当前的 Block。

openBlock 的实现很简单,往当前 blockStack push 一个新的 Block,作为 currentBlock。

那么设计 Block 的目的是什么呢?主要就是收集动态的 vnode 的节点,这样才能在 patch 阶段只比对这些动态 vnode 节点,避免不必要的静态节点的比对,优化了性能。

那么动态 vnode 节点是什么时候被收集的呢?其实是在 createVNode 阶段,我们来回顾一下它的实现:

  1. function createVNode(type, props = null
  2. ,children = null) {
  3. if (shouldTrack > 0 &&
  4. !isBlockNode &&
  5. currentBlock &&
  6. patchFlag !== 32 &&
  7. (patchFlag > 0 ||
  8. shapeFlag & 128 ||
  9. shapeFlag & 64 ||
  10. shapeFlag & 4 ||
  11. shapeFlag & 2 )) {
  12. currentBlock.push(vnode);
  13. }
  14. return vnode
  15. }

注释中写的前面几个过程,我们在之前的章节已经讲过了,我们来看函数的最后,这里会判断 vnode 是不是一个动态节点,如果是则把它添加到 currentBlock 中,这就是动态 vnode 节点的收集过程。

我们接着来看 createBlock 的实现:

  1. function createBlock(type, props, children, patchFlag, dynamicProps) {
  2. const vnode = createVNode(type, props, children, patchFlag, dynamicProps, true )
  3. vnode.dynamicChildren = currentBlock || EMPTY_ARR
  4. blockStack.pop()
  5. currentBlock = blockStack[blockStack.length - 1] || null
  6. if (currentBlock) {
  7. currentBlock.push(vnode)
  8. }
  9. return vnode
  10. }

这时候你可能会好奇,为什么要设计 openBlock 和 createBlock 两个函数呢?比如下面这个函数render()

  1. function render() {
  2. return (openBlock(),createBlock('div', null, []))
  3. }

为什么不把 openBlock 和 createBlock 放在一个函数中执行呢,像下面这样:

  1. function render() {
  2. return (createBlock('div', null, []))
  3. }
  4. function createBlock(type, props, children, patchFlag, dynamicProps) {
  5. openBlock()
  6. const vnode = createVNode(type, props, children, patchFlag, dynamicProps, true)
  7. return vnode
  8. }

这样是不行的!其中原因其实很简单,createBlock 函数的第三个参数是 children,这些 children 中的元素也是经过 createVNode 创建的,显然一个函数的调用需要先去执行参数的计算,也就是优先去创建子节点的 vnode,然后才会执行父节点的 createBlock 或者是 createVNode。

所以在父节点的 createBlock 函数执行前,子节点就已经通过 createVNode 创建了对应的 vnode ,如果把 openBlock 的逻辑放在了 createBlock 中,就相当于在子节点创建后才创建 currentBlock,这样就不能正确地收集子节点中的动态 vnode 了。

再回到 createBlock 函数内部,这个时候你要明白动态子节点已经被收集到 currentBlock 中了。

函数首先会执行 createVNode 创建一个 vnode 节点,注意最后一个参数是 true,这表明它是一个 Block node,所以就不会把自身当作一个动态 vnode 收集到 currentBlock 中。

接着把收集动态子节点的 currentBlock 保留到当前的 Block vnode 的 dynamicChildren 中,为后续 patch 过程访问这些动态子节点所用。

最后把当前 Block 恢复到父 Block,如果父 Block 存在的话,则把当前这个 Block node 作为动态节点添加到父 Block 中。

Block Tree 的构造过程我们搞清楚了,那么接下来我们就来看它在 patch 阶段具体是如何工作的。

我们之前分析过,在 patch 阶段更新节点元素的时候,会执行 patchElement 函数,我们再来回顾一下它的实现:

  1. const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, optimized) => {
  2. const el = (n2.el = n1.el)
  3. const oldProps = (n1 && n1.props) || EMPTY_OBJ
  4. const newProps = n2.props || EMPTY_OBJ
  5. patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG)
  6. const areChildrenSVG = isSVG && n2.type !== 'foreignObject'
  7. if (n2.dynamicChildren) {
  8. patchBlockChildren(n1.dynamicChildren, n2.dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG);
  9. }
  10. else if (!optimized) {
  11. patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG);
  12. }
  13. }

我们在前面组件更新的章节分析过这个流程,在分析子节点更新的部分,当时并没有考虑到优化的场景,所以只分析了全量比对更新的场景。

而实际上,如果这个 vnode 是一个 Block vnode,那么我们不用去通过 patchChildren 全量比对,只需要通过 patchBlockChildren 去比对并更新 Block 中的动态子节点即可。

我们来看一下它的实现:

  1. const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG) => {
  2. for (let i = 0; i < newChildren.length; i++) {
  3. const oldVNode = oldChildren[i]
  4. const newVNode = newChildren[i]
  5. const container =
  6. oldVNode.type === Fragment ||
  7. !isSameVNodeType(oldVNode, newVNode) ||
  8. oldVNode.shapeFlag & 6
  9. ? hostParentNode(oldVNode.el)
  10. :
  11. fallbackContainer
  12. patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, true)
  13. }
  14. }

patchBlockChildren 的实现很简单,遍历新的动态子节点数组,拿到对应的新旧动态子节点,并执行 patch 更新子节点即可。

这样一来,更新的复杂度就变成和动态节点的数量正相关,而不与模板大小正相关,如果一个模板的动静比越低,那么性能优化的效果就越明显。

总结

好的,到这里我们这一节的学习也要结束啦,通过这节课的学习,你应该了解了 AST 是如何生成可运行的代码,也应该明白了 Vue.js 3.0 是如何通过 Block 的方式实现了运行时组件更新的性能优化。

我也推荐你写一些其他的示例,通过断点调试的方式,看看不同的场景的代码生成过程。

最后,给你留一道思考题目,Block 数组是一维的,但是动态的子节点可能有嵌套关系,patchBlockChildren 内部也是递归执行了 patch 函数,那么在整个更新的过程中,会出现子节点重复更新的情况吗,为什么?欢迎你在留言区与我分享。

本节课的相关代码在源代码中的位置如下:
packages/compiler-core/src/codegen.ts
packages/runtime-core/src/vnode.ts
packages/runtime-core/src/renderer.ts