VNode 有哪些属性?
参考答案
常用属性(Vue 3 VNode)
| 属性 | 含义 |
|---|---|
| type | 元素类型:字符串标签名、组件对象、Fragment、Text、Comment、Static |
| props | 属性/事件/指令等(含 class、style、onXxx、key、ref) |
| children | 子节点(数组 / 字符串 / 插槽对象) |
| key | diff 用的唯一标识 |
| ref | 模板 ref 或函数 ref |
| el | 对应的真实 DOM 节点(patch 后填充) |
| shapeFlag | 位标记:ELEMENT/TEXT/COMPONENT/SLOTS_CHILDREN 等,用于快速判断 |
| patchFlag | 编译期标记的动态部分(TEXT/CLASS/PROPS…) |
| dynamicProps | 具体哪些 prop 会变 |
| dynamicChildren | Block 的动态子节点数组 |
| appContext / ctx | 组件上下文(提供全局配置、provide 等) |
| dirs | 自定义指令 |
| transition | 过渡配置 |
| component | 组件实例(组件 vnode 才有) |
| anchor | Fragment 的结束锚点(用于插入定位) |
| target / targetAnchor | Teleport 的目标容器 |
Vue 2 VNode 属性
tag / data / children / text / elm / ns / context / functionalContext / key / componentOptions / componentInstance / parent / raw / isStatic / isRootInsert / isComment / isCloned / isOnce
其中 data 里装 attrs / props / on / nativeOn / class / staticClass / style / staticStyle / directives / keepAlive / transition / scopedSlots / slot / key / ref / refInFor。
为什么 VNode 要这么设计
- 完整描述:渲染所需的一切(类型、属性、子节点、上下文)都在一个对象里,便于 diff 与跨平台;
- 性能:
shapeFlag/patchFlag让运行时用位运算快速分支,避免字符串比较; - 可复用:
el让 VNode 与真实 DOM 双向关联,diff 后可直接操作; - 可序列化:SSR 时 VNode 可序列化成 HTML 字符串。