0
点赞
收藏
分享

微信扫一扫

写后端项目的分页查询时,解决分页不更新

VNode解析—上


在 Vue 3 中,VNode(虚拟节点)是框架内部用于表示真实 DOM 结构的 JavaScript 对象。VNode 使得 Vue 能够在不直接操作 DOM 的情况下,通过比较新旧 VNode 来决定是否需要更新 DOM。这种机制提高了渲染性能,并简化了数据与视图之间的同步过程。

1. VNode 的作用和优势

1.1 抽象表示

VNode 是对真实 DOM 的抽象表示,允许 Vue 在内存中操作 DOM 结构,而无需直接与真实 DOM 交互,从而提高效率。

1.2 更新优化

通过对比新旧 VNode,Vue 可以确定哪些部分需要更新,避免不必要的 DOM 操作,优化渲染性能。

1.3 跨平台

VNode 机制使得 Vue 不依赖于特定平台的 DOM 实现,支持如服务器端渲染(SSR)、原生应用(如通过 Vue Native 或 Weex)等跨平台应用。

2. _createVNode 函数解析

_createVNode 是 VNode 创建过程中的核心函数,负责根据输入参数生成 VNode 对象。以下是 _createVNode 的调用链路和详细解析:

2.1 调用链路

当 Vue 应用的 .mount() 方法被调用时,它首先通过 createVNode 函数创建根组件的 VNode:

//apiCreateApp.ts
const vnode = createVNode(rootComponent, rootProps)

//vnode.ts
export const createVNode = (
  __DEV__ ? createVNodeWithArgsTransform : _createVNode
) as typeof _createVNode

createVNode 函数根据环境配置决定具体的实现,生产环境下直接使用 _createVNode。

2.2 _createVNode函数实现

_createVNode 主要执行以下操作:

function _createVNode(
  type: VNodeTypes | ClassComponent | typeof NULL_DYNAMIC_COMPONENT,
  props: (Data & VNodeProps) | null = null,
  children: unknown = null,
  patchFlag: number = 0,
  dynamicProps: string[] | null = null,
  isBlockNode = false,
): VNode {
   
  /**
   * 检查 type 是否有效。
   * 如果不是有效的节点类型,将 type 设置为 Comment(注释节点),用于表示无效或空节点。
   */
  if (!type || type === NULL_DYNAMIC_COMPONENT) {
   
    if (__DEV__ && !type) {
   
      warn(`Invalid vnode type when creating vnode: ${
     type}.`)
    }
    type = Comment
  }
 
  /**
   * 处理传入的 VNode 类型,如果是已存在的 VNode对象,则克隆这个 VNode,并根据需要合并引用和处理子节点。
   */
  if (isVNode(type)) {
   
    // createVNode receiving an existing vnode. This happens in cases like
    // <component :is="vnode"/>
    // #2078 make sure to merge refs during the clone instead of overwriting it
    const cloned = cloneVNode(type, props, true /* mergeRef: true */)
    if (children) {
   
      normalizeChildren(
举报

相关推荐

0 条评论