当前位置:主页 > 查看内容

Vue 3.0 进阶之 VNode 探秘

发布时间:2021-05-17 00:00| 位朋友查看

简介:本文转载自微信公众号「全栈修仙之路」,作者阿宝哥 。转载本文请联系全栈修仙之路公众号。 本文是 Vue 3.0 进阶系列 的第五篇文章,在这篇文章中,阿宝哥将介绍 Vue 3 中的核心对象 VNode,该对象用于描述节点的信息,它的全称是虚拟节点(virtual node)。与……

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

本文是 Vue 3.0 进阶系列 的第五篇文章,在这篇文章中,阿宝哥将介绍 Vue 3 中的核心对象 —— VNode,该对象用于描述节点的信息,它的全称是虚拟节点(virtual node)。与 “虚拟节点” 相关联的另一个概念是 “虚拟 DOM”,它是我们对由 Vue 组件树建立起来的整个 VNode 树的称呼。通常一个 Vue 应用会以一棵嵌套的组件树的形式来组织

(图片来源:https://v3.cn.vuejs.org/)

所以 “虚拟 DOM” 对 Vue 应用来说,是至关重要的。而 “虚拟 DOM” 又是由 VNode 组成的,它是 Vue 底层的核心基石。接下来,阿宝哥将带大家一起来探索 Vue 3 中与 VNode 相关的一些知识。

一、VNode 长什么样?

  1. // packages/runtime-core/src/vnode.ts 
  2. export interface VNode< 
  3.   HostNode = RendererNode, 
  4.   HostElement = RendererElement, 
  5.   ExtraProps = { [key: string]: any } 
  6. > { 
  7.  // 省略内部的属性 

在 runtime-core/src/vnode.ts 文件中,我们找到了 VNode 的类型定义。通过 VNode 的类型定义可知,VNode 本质是一个对象,该对象中按照属性的作用,分为 5 大类。这里阿宝哥只详细介绍其中常见的两大类型属性 —— 内部属性 和 DOM 属性:

1.1 内部属性

  1. __v_isVNode: true // 标识是否为VNode 
  2. [ReactiveFlags.SKIP]: true // 标识VNode不是observable 
  3. type: VNodeTypes // VNode 类型 
  4. props: (VNodeProps & ExtraProps) | null // 属性信息 
  5. key: string | number | null // 特殊 attribute 主要用在 Vue 的虚拟 DOM 算法 
  6. ref: VNodeNormalizedRef | null // 被用来给元素或子组件注册引用信息。 
  7. scopeId: string | null // SFC only 
  8. children: VNodeNormalizedChildren // 保存子节点 
  9. component: ComponentInternalInstance | null // 指向VNode对应的组件实例 
  10. dirs: DirectiveBinding[] | null // 保存应用在VNode的指令信息 
  11. transition: TransitionHooks<HostElement> | null // 存储过渡效果信息 

1.2 DOM 属性

  1. el: HostNode | null // element  
  2. anchor: HostNode | null // fragment anchor 
  3. target: HostElement | null // teleport target 
  4. targetAnchor: HostNode | null // teleport target anchor 
  5. staticCount: number // number of elements contained in a static vnode 

1.3 suspense 属性

  1. suspense: SuspenseBoundary | null 
  2. ssContent: VNode | null 
  3. ssFallback: VNode | null 

1.4 optimization 属性

  1. shapeFlag: number 
  2. patchFlag: number 
  3. dynamicProps: string[] | null 
  4. dynamicChildren: VNode[] | null 

1.5 应用上下文属性

  1. appContext: AppContext | null 

二、如何创建 VNode?

要创建 VNode 对象的话,我们可以使用 Vue 提供的 h 函数。也许可以更准确地将其命名为 createVNode(),但由于频繁使用和简洁,它被称为 h() 。该函数接受三个参数:

  1. // packages/runtime-core/src/h.ts 
  2. export function h(type: any, propsOrChildren?: any, children?: any): VNode { 
  3.   const l = arguments.length 
  4.   if (l === 2) {  
  5.     if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {  
  6.       // single vnode without props 
  7.       if (isVNode(propsOrChildren)) { 
  8.         return createVNode(type, null, [propsOrChildren]) 
  9.       } 
  10.       // 只包含属性不含有子元素 
  11.       return createVNode(type, propsOrChildren) // h('div', { id: 'foo' }) 
  12.     } else { 
  13.       // 忽略属性 
  14.       return createVNode(type, null, propsOrChildren) // h('div', ['foo']) 
  15.     } 
  16.   } else { 
  17.     if (l > 3) { 
  18.       children = Array.prototype.slice.call(arguments, 2) 
  19.     } else if (l === 3 && isVNode(children)) { 
  20.       children = [children] 
  21.     } 
  22.     return createVNode(type, propsOrChildren, children) 
  23.   } 

观察以上代码可知, h 函数内部的主要处理逻辑就是根据参数个数和参数类型,执行相应处理操作,但最终都是通过调用 createVNode 函数来创建 VNode 对象。在开始介绍 createVNode 函数前,阿宝哥先举一些实际开发中的示例:

  1. const app = createApp({ // 示例一 
  2.   render: () => h('div''我是阿宝哥'
  3. }) 
  4.  
  5. const Comp = () => h("p""我是阿宝哥"); // 示例二 
  6.  
  7. app.component('component-a', { // 示例三 
  8.   template: "<p>我是阿宝哥</p>" 
  9. }) 

示例一和示例二很明显都使用了 h 函数,而示例三并未看到 h 或 createVNode 函数的身影。为了一探究竟,我们需要借助 Vue 3 Template Explorer 这个在线工具来编译一下 "

<p>我是阿宝哥</p>" 模板,该模板编译后的结果如下(函数模式):

  1. // https://vue-next-template-explorer.netlify.app/ 
  2. const _Vue = Vue 
  3. return function render(_ctx, _cache, $props, $setup, $data, $options) { 
  4.   with (_ctx) { 
  5.     const { createVNode: _createVNode, openBlock: _openBlock, 
  6.       createBlock: _createBlock } = _Vue 
  7.     return (_openBlock(), _createBlock("p"null"我是阿宝哥")) 
  8.   } 

由以上编译结果可知, "<p>我是阿宝哥</p>" 模板被编译生成了一个 render 函数,调用该函数后会返回 createBlock 函数的调用结果。其中 createBlock 函数的实现如下所示:

  1. // packages/runtime-core/src/vnode.ts 
  2. export function createBlock( 
  3.   type: VNodeTypes | ClassComponent, 
  4.   props?: Record<string, any> | null
  5.   children?: any
  6.   patchFlag?: number, 
  7.   dynamicProps?: string[] 
  8. ): VNode { 
  9.   const vnode = createVNode( 
  10.     type, 
  11.     props, 
  12.     children, 
  13.     patchFlag, 
  14.     dynamicProps, 
  15.     true /* isBlock: prevent a block from tracking itself */ 
  16.   ) 
  17.   // 省略部分代码 
  18.   return vnode 

在 createBlock 函数内部,我们终于看到了 createVNode 函数的身影。顾名思义,该函数的作用就是用于创建 VNode,接下来我们来分析一下它。

三、createVNode 函数内部做了啥?

下面我们将从参数说明和逻辑说明两方面来介绍 createVNode 函数:

3.1 参数说明

  1. // packages/runtime-core/src/vnode.ts 
  2. export const createVNode = (__DEV__ 
  3.   ? createVNodeWithArgsTransform 
  4.   : _createVNode) as typeof _createVNode 
  5.  
  6. function _createVNode( 
  7.   type: VNodeTypes | ClassComponent | typeof NULL_DYNAMIC_COMPONENT, 
  8.   props: (Data & VNodeProps) | null = null
  9.   children: unknown = null
  10.   patchFlag: number = 0, 
  11.   dynamicProps: string[] | null = null
  12.   isBlockNode = false 
  13. ): VNode { 
  14.   //  
  15.   return vnode 

在分析该函数的具体代码前,我们先来看一下它的参数。该函数可以接收 6 个参数,这里阿宝哥用思维导图来重点介绍前面 2 个参数:

type 参数

  1. // packages/runtime-core/src/vnode.ts 
  2. function _createVNode( 
  3.   type: VNodeTypes | ClassComponent | typeof NULL_DYNAMIC_COMPONENT, 
  4.   // 省略其他参数 
  5. ): VNode { ... } 

由上图可知,type 参数支持很多类型,比如常用的 string、VNode 和 Component 等。此外,也有一些陌生的面孔,比如 Text、Comment 、Static 和 Fragment 等类型,它们的定义如下:

  1. // packages/runtime-core/src/vnode.ts 
  2. export const Text = Symbol(__DEV__ ? 'Text' : undefined) 
  3. export const Comment = Symbol(__DEV__ ? 'Comment' : undefined) 
  4. export const Static = Symbol(__DEV__ ? 'Static' : undefined) 
  5.  
  6. export const Fragment = (Symbol(__DEV__ ? 'Fragment' : undefined) as anyas { 
  7.   __isFragment: true 
  8.   new (): { 
  9.     $props: VNodeProps 
  10.   } 

那么定义那么多的类型有什么意义呢?这是因为在 patch 阶段,会根据不同的 VNode 类型来执行不同的操作:

  1. // packages/runtime-core/src/renderer.ts 
  2. function baseCreateRenderer( 
  3.   options: RendererOptions, 
  4.   createHydrationFns?: typeof createHydrationFunctions 
  5. ): any { 
  6.   const patch: PatchFn = ( 
  7.     n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null
  8.     isSVG = false, optimized = false 
  9.   ) => { 
  10.     // 省略部分代码 
  11.     const { type, ref, shapeFlag } = n2 
  12.     switch (type) { 
  13.       case Text: // 处理文本节点 
  14.         processText(n1, n2, container, anchor) 
  15.         break 
  16.       case Comment: // 处理注释节点 
  17.         processCommentNode(n1, n2, container, anchor) 
  18.         break 
  19.       case Static: // 处理静态节点 
  20.         if (n1 == null) { 
  21.           mountStaticNode(n2, container, anchor, isSVG) 
  22.         } else if (__DEV__) { 
  23.           patchStaticNode(n1, n2, container, isSVG) 
  24.         } 
  25.         break 
  26.       case Fragment: // 处理Fragment节点 
  27.         processFragment(...) 
  28.         break 
  29.       default
  30.         if (shapeFlag & ShapeFlags.ELEMENT) { // 元素类型 
  31.           processElement(...) 
  32.         } else if (shapeFlag & ShapeFlags.COMPONENT) { // 组件类型 
  33.           processComponent(...) 
  34.         } else if (shapeFlag & ShapeFlags.TELEPORT) { // teleport内置组件 
  35.           ;(type as typeof TeleportImpl).process(...) 
  36.         } else if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) { 
  37.           ;(type as typeof SuspenseImpl).process(...) 
  38.         } 
  39.     } 
  40.   } 

介绍完 type 参数后,接下来我们来看 props 参数,具体如下图所示:

props 参数

  1. function _createVNode( 
  2.   type: VNodeTypes | ClassComponent | typeof NULL_DYNAMIC_COMPONENT, 
  3.   props: (Data & VNodeProps) | null = null
  4. ): VNode { ... } 

props 参数的类型是联合类型,这里我们来分析 Data & VNodeProps 交叉类型:

其中 Data 类型是通过 TypeScript 内置的工具类型 Record 来定义的:

  1. export type Data = Record<string, unknown> 
  2. type Record<K extends keyof any, T> = { 
  3.   [P in K]: T; 
  4. }; 

而 VNodeProps 类型是通过类型别名来定义的,除了含有 key 和 ref 属性之外,其他的属性主要是定义了与生命周期有关的钩子:

  1. // packages/runtime-core/src/vnode.ts 
  2. export type VNodeProps = { 
  3.   key?: string | number 
  4.   ref?: VNodeRef 
  5.  
  6.   // vnode hooks 
  7.   onVnodeBeforeMount?: VNodeMountHook | VNodeMountHook[] 
  8.   onVnodeMounted?: VNodeMountHook | VNodeMountHook[] 
  9.   onVnodeBeforeUpdate?: VNodeUpdateHook | VNodeUpdateHook[] 
  10.   onVnodeUpdated?: VNodeUpdateHook | VNodeUpdateHook[] 
  11.   onVnodeBeforeUnmount?: VNodeMountHook | VNodeMountHook[] 
  12.   onVnodeUnmounted?: VNodeMountHook | VNodeMountHook[] 

3.2 逻辑说明

createVNode 函数内部涉及较多的处理逻辑,这里我们只分析主要的逻辑:

  1. // packages/runtime-core/src/vnode.ts 
  2. function _createVNode( 
  3.   type: VNodeTypes | ClassComponent | typeof NULL_DYNAMIC_COMPONENT, 
  4.   props: (Data & VNodeProps) | null = null
  5.   children: unknown = null
  6.   patchFlag: number = 0, 
  7.   dynamicProps: string[] | null = null
  8.   isBlockNode = false 
  9. ): VNode { 
  10.   // 处理VNode类型,比如处理动态组件的场景:<component :is="vnode"/> 
  11.   if (isVNode(type)) { 
  12.     const cloned = cloneVNode(type, props, true /* mergeRef: true */) 
  13.     if (children) { 
  14.       normalizeChildren(cloned, children) 
  15.     } 
  16.     return cloned 
  17.   } 
  18.  
  19.   // 类组件规范化处理 
  20.   if (isClassComponent(type)) { 
  21.     type = type.__vccOpts 
  22.   } 
  23.  
  24.   // 类和样式规范化处理 
  25.   if (props) { 
  26.     // 省略相关代码 
  27.   } 
  28.  
  29.   // 把vnode的类型信息转换为位图 
  30.   const shapeFlag = isString(type) 
  31.     ? ShapeFlags.ELEMENT // ELEMENT = 1 
  32.     : __FEATURE_SUSPENSE__ && isSuspense(type) 
  33.       ? ShapeFlags.SUSPENSE // SUSPENSE = 1 << 7, 
  34.       : isTeleport(type) 
  35.         ? ShapeFlags.TELEPORT // TELEPORT = 1 << 6, 
  36.         : isObject(type) 
  37.           ? ShapeFlags.STATEFUL_COMPONENT // STATEFUL_COMPONENT = 1 << 2, 
  38.           : isFunction(type) 
  39.             ? ShapeFlags.FUNCTIONAL_COMPONENT // FUNCTIONAL_COMPONENT = 1 << 1, 
  40.             : 0 
  41.  
  42.   // 创建VNode对象 
  43.   const vnode: VNode = { 
  44.     __v_isVNode: true
  45.     [ReactiveFlags.SKIP]: true
  46.     type, 
  47.     props, 
  48.     // ... 
  49.   } 
  50.  
  51.   // 子元素规范化处理 
  52.   normalizeChildren(vnode, children) 
  53.   return vnode 

介绍完 createVNode 函数之后,阿宝哥再来介绍另一个比较重要的函数 —— normalizeVNode。

四、如何创建规范的 VNode 对象?

normalizeVNode 函数的作用,用于将传入的 child 参数转换为规范的 VNode 对象。

  1. // packages/runtime-core/src/vnode.ts 
  2. export function normalizeVNode(child: VNodeChild): VNode { 
  3.   if (child == null || typeof child === 'boolean') { // null/undefined/boolean -> Comment 
  4.     return createVNode(Comment) 
  5.   } else if (isArray(child)) { // array -> Fragment 
  6.     return createVNode(Fragment, null, child) 
  7.   } else if (typeof child === 'object') { // VNode -> VNode or mounted VNode -> cloned VNode 
  8.     return child.el === null ? child : cloneVNode(child) 
  9.   } else { // primitive types:'foo' or 1 
  10.     return createVNode(Text, null, String(child)) 
  11.   } 

由以上代码可知,normalizeVNode 函数内部会根据 child 参数的类型进行不同的处理:

4.1 null / undefined -> Comment

  1. expect(normalizeVNode(null)).toMatchObject({ type: Comment }) 
  2. expect(normalizeVNode(undefined)).toMatchObject({ type: Comment }) 

4.2 boolean -> Comment

  1. expect(normalizeVNode(true)).toMatchObject({ type: Comment }) 
  2. expect(normalizeVNode(false)).toMatchObject({ type: Comment }) 

4.3 array -> Fragment

  1. expect(normalizeVNode(['foo'])).toMatchObject({ type: Fragment }) 

4.4 VNode -> VNode

  1. const vnode = createVNode('div'
  2. expect(normalizeVNode(vnode)).toBe(vnode) 

4.5 mounted VNode -> cloned VNode

  1. const mounted = createVNode('div'
  2. mounted.el = {} 
  3. const normalized = normalizeVNode(mounted) 
  4. expect(normalized).not.toBe(mounted) 
  5. expect(normalized).toEqual(mounted) 

4.6 primitive types

  1. expect(normalizeVNode('foo')).toMatchObject({ type: Text, children: `foo` }) 
  2. expect(normalizeVNode(1)).toMatchObject({ type: Text, children: `1` }) 

五、阿宝哥有话说

5.1 如何判断是否为 VNode 对象?

  1. // packages/runtime-core/src/vnode.ts 
  2. export function isVNode(value: any): value is VNode { 
  3.   return value ? value.__v_isVNode === true : false 

在 VNode 对象中含有一个 __v_isVNode 内部属性,利用该属性可以用来判断当前对象是否为 VNode 对象。

5.2 如何判断两个 VNode 对象的类型是否相同?

  1. // packages/runtime-core/src/vnode.ts 
  2. export function isSameVNodeType(n1: VNode, n2: VNode): boolean { 
  3.   // 省略__DEV__环境的处理逻辑 
  4.   return n1.type === n2.type && n1.key === n2.key 

在 Vue 3 中,是通过比较 VNode 对象的 type 和 key 属性,来判断两个 VNode 对象的类型是否相同。

5.3 如何快速创建某些类型的 VNode 对象?

在 Vue 3 内部提供了 createTextVNode 、createCommentVNode 和 createStaticVNode 函数来快速的创建文本节点、注释节点和静态节点:

createTextVNode

  1. export function createTextVNode(text: string = ' ', flag: number = 0): VNode { 
  2.   return createVNode(Text, null, text, flag) 

createCommentVNode

  1. export function createCommentVNode( 
  2.   text: string = ''
  3.   asBlock: boolean = false 
  4. ): VNode { 
  5.   return asBlock 
  6.     ? (openBlock(), createBlock(Comment, null, text)) 
  7.     : createVNode(Comment, null, text) 

createStaticVNode

  1. export function createStaticVNode( 
  2.   content: string, 
  3.   numberOfNodes: number 
  4. ): VNode { 
  5.   const vnode = createVNode(Staticnull, content) 
  6.   vnode.staticCount = numberOfNodes 
  7.   return vnode 

本文阿宝哥主要介绍了 VNode 对象是什么、如何创建 VNode 对象及如何创建规范的 VNode 对象。为了让大家能够更深入地理解 h 和 createVNode 函数的相关知识,阿宝哥还从源码的角度分析了 createVNode 函数 。

在后续的文章中,阿宝哥将会介绍 VNode 在 Vue 3 内部是如何被使用的,感兴趣的小伙伴不要错过哟。

六、参考资源

Vue 3 官网 - 渲染函数


本文转载自网络,原文链接:https://mp.weixin.qq.com/s/8OP6a27bkmfUKQRRZFKqkw
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文


随机推荐