Render 渲染原理

583 阅读4分钟

《mount 挂载实现原理》一文中,详细地讲解其背后是如何实现的。其中留下三个核心逻辑未具体展开,本文将讲解其中一个,即 render 函数如何将 Vue 实例渲染成虚拟 DOM。

render 内部实现

按照惯例,沿着主线将 render 实现逻辑整理成一张图,如下:

render.png

源码实现如下:

  Vue.prototype._render = function (): VNode {
    const vm: Component = this
    const { render, _parentVnode } = vm.$options

    if (_parentVnode) {
      vm.$scopedSlots = normalizeScopedSlots(
        _parentVnode.data.scopedSlots,
        vm.$slots,
        vm.$scopedSlots
      )
    }

    // set parent vnode. this allows render functions to have access
    // to the data on the placeholder node.
    vm.$vnode = _parentVnode
    // render self
    let vnode
    try {
      // There's no need to maintain a stack because all render fns are called
      // separately from one another. Nested component's render fns are called
      // when parent component is patched.
      currentRenderingInstance = vm
      vnode = render.call(vm._renderProxy, vm.$createElement)
    } catch (e) {
      handleError(e, vm, `render`)
      // return error render result,
      // or previous vnode to prevent render error causing blank component
      /* istanbul ignore else */
      if (process.env.NODE_ENV !== 'production' && vm.$options.renderError) {
        try {
          vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)
        } catch (e) {
          handleError(e, vm, `renderError`)
          vnode = vm._vnode
        }
      } else {
        vnode = vm._vnode
      }
    } finally {
      currentRenderingInstance = null
    }
    // if the returned array contains only a single node, allow it
    if (Array.isArray(vnode) && vnode.length === 1) {
      vnode = vnode[0]
    }
    // return empty vnode in case the render function errored out
    if (!(vnode instanceof VNode)) {
      if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
        warn(
          'Multiple root nodes returned from render function. Render function ' +
          'should return a single root node.',
          vm
        )
      }
      vnode = createEmptyVNode()
    }
    // set parent
    vnode.parent = _parentVnode
    return vnode
  }

render 函数实现主要有以下几点:

  • vm 实例上属性 $options 进行解构,获取 render 函数和 _parentVnode
  • 如果 _parentVnodetrue,会对插槽进行规范化处理
  • 执行 render 函数,需要传递两个参数:vm._renderProxyvm.$createElemen,返回 vnod
  • render 函数渲染生成的虚拟 DOM 返回

对于 vm._renderProxy,在初始化 Vue 实例时就已经定义了,即 Vue.prototype._init 方法里面,位于 src/core/instance/init.js

/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
  initProxy(vm)
} else {
  vm._renderProxy = vm
}

如果在生产环境,vm._renderProxy 等同于 vm 实例;如果在开发环境,则调用 initProxy 来初始化 vm._renderProxy

initProxy = function initProxy (vm) {
  if (hasProxy) {
    // determine which proxy handler to use
    const options = vm.$options
    const handlers = options.render && options.render._withStripped
      ? getHandler
      : hasHandler
    vm._renderProxy = new Proxy(vm, handlers)
  } else {
    vm._renderProxy = vm
  }
}

如果所处环境支持 Proxy ,那么 vm._renderProxy 将初始化为 vm 实例的代理;否则直接初始化为 vm 实例。

对于 vm.$createElement ,同样也在实例化 Vue 时就已经定义了,即在 initRender 方法里面,位于 src/core/instance/init.js

export function initRender (vm: Component) {
  ...
  // bind the createElement fn to this instance
  // so that we get proper render context inside it.
  // args order: tag, data, children, normalizationType, alwaysNormalize
  // internal version is used by render functions compiled from templates
  vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
  // normalization is always applied for the public version, used in
  // user-written render functions.
  vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)
  ...
}

vm.$createElement 方法用于用户手写 render 时使用,其内部调用方法 createElement ;除此之外,我们还可以看到提供另外一个方法:vm._C ,它是一个内部版本,其作用是用于将 template 编译成 render 函数,同样也是调用方法 createElement

createElement 方法的作用是返回创建的虚拟 Node,其实现逻辑相对比较复杂。

createElement 内部实现

// wrapper function for providing a more flexible interface
// without getting yelled at by flow
export function createElement (
  context: Component,
  tag: any,
  data: any,
  children: any,
  normalizationType: any,
  alwaysNormalize: boolean
): VNode | Array<VNode> {
  if (Array.isArray(data) || isPrimitive(data)) {
    normalizationType = children
    children = data
    data = undefined
  }
  if (isTrue(alwaysNormalize)) {
    normalizationType = ALWAYS_NORMALIZE
  }
  return _createElement(context, tag, data, children, normalizationType)
}

方法 createElement 接收 6 个参数:

  • contextVode 上下文环境,其数据类型是 Component
  • tag:标签,它可以是一个字符串,也可以是一个 Component
  • dataVNode 的数据
  • children:表示当前 VNode子节点
  • normalizationType:节点规范化类型,提供两个值:SIMPLE_NORMALIZE(1)和 ALWAYS_NORMALIZE(2)
  • alwaysNormalize:是否规范化,true 或者 false

实现逻辑主要有以下几点:

  • 如果 data 数据类型是数组或者基本数据类型,则对参数进行处理;
  • 如果alwaysNormalize 值为 true 时,则对 normalizationType 赋值为 ALWAYS_NORMALIZE ,即 2
  • 调用内部封装方法 _createElement 创建虚拟 Node

_createElement 内部实现

方法 _createElement 接收 5 个参数:

  • context:VNode 上下文环境,其数据类型是 Component
  • tag:表示标签,可以是一个字符串,也可以是一个 Component 类型
  • data:VNode 的数据,其数据类型是 VNodeData
  • children:表示当前 VNode 的子节点,它可以是任何数据类型
  • normalizationType:表示子节点规范的类型,类型不同调用的规范方法也不同

接下来分析方法的具体实现

if (isDef(data) && isDef((data: any).__ob__)) {
  process.env.NODE_ENV !== 'production' && warn(
    `Avoid using observed data object as vnode data: ${JSON.stringify(data)}\n` +
    'Always create fresh vnode data objects in each render!',
    context
  )
  return createEmptyVNode()
}

检查 VNode 的 data 属性是否是响应性,如果是响应式的话,则抛出警告(避免把 VNode 的 data 属性设置成响应式,否则始终会在每次渲染时创建新的 Vnode 数据对象。 ),并且创建注释节点返回。

// object syntax in v-bind
if (isDef(data) && isDef(data.is)) {
  tag = data.is
}

检查 Vnode 中 data 属性是否包含 v-bind:is,如果是的话则将其赋值给 tag。其作用是用于动态组件,传递已注册组件名称或者组件的选项对象。

// warn against non-primitive key
if (process.env.NODE_ENV !== 'production' &&
    isDef(data) && isDef(data.key) && !isPrimitive(data.key)
) {
  if (!__WEEX__ || !('@binding' in data.key)) {
    warn(
      'Avoid using non-primitive value as key, ' +
      'use string/number value instead.',
      context
    )
  }
}

比如使用指令 v-for 等需要设置 key 时,其数据类型只能是 string 或者 number

if (normalizationType === ALWAYS_NORMALIZE) {
  children = normalizeChildren(children)
} else if (normalizationType === SIMPLE_NORMALIZE) {
  children = simpleNormalizeChildren(children)
}

这段逻辑的作用是对子节点进行规范,以符合 VNode 数组标准。有两种类型,先来看下 simpleNormalizeChildren 方法的具体实现

// 1. When the children contains components - because a functional component
// may return an Array instead of a single root. In this case, just a simple
// normalization is needed - if any child is an Array, we flatten the whole
// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
// because functional components already normalize their own children.
export function simpleNormalizeChildren (children: any) {
  for (let i = 0; i < children.length; i++) {
    if (Array.isArray(children[i])) {
      return Array.prototype.concat.apply([], children)
    }
  }
  return children
}

该方法的使用场景是 render 函数由 template 编译而成的,理论上编译生成的 children 是 VNode 类型的。但是有个例外,就是函数式组件 function component 返回的是一个数组,而不是一个跟节点;这时就需要 Array.prototype.concat 方法将 children 打平,使其深度只有一层。

接着再来看下 normalizeChildren 方法的具体实现:

// 2. When the children contains constructs that always generated nested Arrays,
// e.g. <template>, <slot>, v-for, or when the children is provided by user
// with hand-written render functions / JSX. In such cases a full normalization
// is needed to cater to all possible types of children values.
export function normalizeChildren (children: any): ?Array<VNode> {
  return isPrimitive(children)
    ? [createTextVNode(children)]
    : Array.isArray(children)
      ? normalizeArrayChildren(children)
      : undefined
}

该方法调用的场景有两种:一是 render 函数是用户手写的,且 children 只有一个节点,那么此时调用 createTextVNode 创建简单的文本节点;另一种是当使用 templateslotv-fot 时,在编译的时候会生成嵌套数组,需要调用方法 normalizeArrayChildren 进行处理。

function normalizeArrayChildren (children: any, nestedIndex?: string): Array<VNode> {
  const res = []
  let i, c, lastIndex, last
  for (i = 0; i < children.length; i++) {
    c = children[i]
    if (isUndef(c) || typeof c === 'boolean') continue
    lastIndex = res.length - 1
    last = res[lastIndex]
    //  nested
    if (Array.isArray(c)) {
      if (c.length > 0) {
        c = normalizeArrayChildren(c, `${nestedIndex || ''}_${i}`)
        // merge adjacent text nodes
        if (isTextNode(c[0]) && isTextNode(last)) {
          res[lastIndex] = createTextVNode(last.text + (c[0]: any).text)
          c.shift()
        }
        res.push.apply(res, c)
      }
    } else if (isPrimitive(c)) {
      if (isTextNode(last)) {
        // merge adjacent text nodes
        // this is necessary for SSR hydration because text nodes are
        // essentially merged when rendered to HTML strings
        res[lastIndex] = createTextVNode(last.text + c)
      } else if (c !== '') {
        // convert primitive to vnode
        res.push(createTextVNode(c))
      }
    } else {
      if (isTextNode(c) && isTextNode(last)) {
        // merge adjacent text nodes
        res[lastIndex] = createTextVNode(last.text + c.text)
      } else {
        // default key for nested array children (likely generated by v-for)
        if (isTrue(children._isVList) &&
          isDef(c.tag) &&
          isUndef(c.key) &&
          isDef(nestedIndex)) {
          c.key = `__vlist${nestedIndex}_${i}__`
        }
        res.push(c)
      }
    }
  }
  return res
}

该方法的作用是遍历 children,获取每个单独的节点 c,判断 c 的数据类型。如果 c 是数组,则递归调用 normalizeArrayChildren 进行处理;如果 c 是基础类型,则调用方法 createTextVNode 将其转换为 VNode 类型;如果 children 是一个列表并且列表还存在嵌套的情况下,则需要根据 nestedIndex 更新 key

在遍历的过程中,对于连续的两个 text 节点,则将其合并成一个 text 节点,算是一种优化。最后返回规范化后 VNode 类型的数组。

  if (typeof tag === 'string') {
    let Ctor
    ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag)
    if (config.isReservedTag(tag)) {
      // platform built-in elements
      if (process.env.NODE_ENV !== 'production' && isDef(data) && isDef(data.nativeOn) && data.tag !== 'component') {
        warn(
          `The .native modifier for v-on is only valid on components but it was used on <${tag}>.`,
          context
        )
      }
      vnode = new VNode(
        config.parsePlatformTagName(tag), data, children,
        undefined, undefined, context
      )
    } else if ((!data || !data.pre) && isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
      // component
      vnode = createComponent(Ctor, data, context, children, tag)
    } else {
      // unknown or unlisted namespaced elements
      // check at runtime because it may get assigned a namespace when its
      // parent normalizes children
      vnode = new VNode(
        tag, data, children,
        undefined, undefined, context
      )
    }
  } else {
    // direct component options / constructor
    vnode = createComponent(tag, data, context, children)
  }

那么对子节点规范化处理后,返回 VNode 类型的数组,根据返回的结果来创建虚拟 DOM。

在创建 VNode 实例的过程中,根据 tag 类型的不同调用不同的处理逻辑创建 VNode。如果 tag 类型是 string,则接着判断如果是内置的一些节点,则直接创建普通的 VNode;如果是为已注册的组件名,则通过 createComponent 创建一个组件类型的 VNode,否则创建一个未知的标签的 VNode。如果 tag 是一个 Component 类型,则直接调用 createComponent 创建一个组件类型的 VNode。

最后将创建好的 VNode 返回。

至此,对 Vue 实例渲染成虚拟 DOM 的实现逻辑有了一定的认识,下一篇文章将讲解如何将虚拟 DOM 渲染成真实 DOM 的。

参考链接

render

createElement