VNode 的属性

Vue 中 VNode 对象包含的属性及其作用

问题

Vue 的 VNode 对象包含哪些属性?

解答

Vue 内部定义的 VNode 对象包含 20 多个属性,可以分为以下几类:

内部标识属性

  • __v_isVNode: true - 标识这是一个 VNode 对象
  • __v_skip: true - 标识跳过响应式转换,reactive 转换时会根据此属性判断
  • isCompatRoot?: true - 标识是否做了兼容处理

核心属性

  • type: VNodeTypes - 虚拟节点的类型
  • props: (VNodeProps & ExtraProps) | null - 虚拟节点的 props
  • key: string | number | null - 用于 diff 算法的 key
  • ref: VNodeNormalizedRef | null - 虚拟节点的引用
  • children: VNodeNormalizedChildren - 子节点
  • component: ComponentInternalInstance | null - 组件实例
  • dirs: DirectiveBinding[] | null - 当前 VNode 绑定的指令
  • transition: TransitionHooks<HostElement> | null - 过渡钩子

作用域相关

  • scopeId: string | null - 仅限于 SFC(单文件组件),在设置 currentRenderingInstance 时一起设置
  • slotScopeIds: string | null - 仅限于单文件组件,与插槽有关

DOM 相关属性

  • el: HostNode | null - 宿主节点
  • anchor: HostNode | null - fragment 锚点
  • target: HostElement | null - teleport 传送的目标
  • targetAnchor: HostNode | null - teleport 目标锚点
  • staticCount: number - 包含的静态节点数量

Suspense 相关属性

  • suspense: SuspenseBoundary | null - suspense 边界
  • ssContent: VNode | null - suspense 内容
  • ssFallback: VNode | null - suspense 降级内容

优化相关属性

  • shapeFlag: number - 形状标记
  • patchFlag: number - 补丁标记
  • dynamicProps: string[] | null - 动态属性
  • dynamicChildren: VNode[] | null - 动态子节点

根节点属性

  • appContext: AppContext | null - 应用实例上下文

Vue 提供了 h 函数来创建 VNode,用户无需手动构造完整的 VNode 对象,但保留了通过 h 函数自定义渲染的能力,为高阶用法提供了灵活性。

关键点

  • VNode 包含 20 多个属性,涵盖类型、props、children、DOM 引用等核心信息
  • 内部属性(__v_isVNode__v_skip)用于 Vue 内部识别和优化
  • 优化属性(shapeFlagpatchFlag)用于提升 diff 性能
  • 用户通常通过 h 函数创建 VNode,无需关心所有属性细节
  • SFC 和 Suspense 等特性有专门的属性支持