Vue源码学习之createElement

Vue源码学习之createElement

在Vue应用开发中,我们大部分时间都是使用template来创建HTML,但是在一些场景中,我们可能会需要在js进行模板的编写及渲染,这时候我们就会用到Vue中的渲染函数render,像下面这样:

Vue.component('renderTest', {
  render: function (createElement) {
    return createdElement('h1', 'this is test render')
  }
})

可以看到在render函数里面我们主要用到了createElement来进行模板的创建,那createElement里面到底进行了什么操作来进行temlate的创建的呢?

VNode

首先我们要知道createElement返回的其实不是一个真实的DOM元素,而是一个js对象,我们把这样的对象称为“虚拟节点(Virtual Node)”,VNode是对真实DOM的一种抽象描述,它包含了真实DOM节点所对应的各种属性,标签名、数据、子节点、键值等。VNode在src/core/vdom/vnode.js中定义

export default class VNode {
  tag: string | void;
  data: VNodeData | void;
  children: ?Array<VNode>;
  text: string | void;
  elm: Node | void;
  ns: string | void;
  context: Component | void; // rendered in this component's scope
  key: string | number | void;
  componentOptions: VNodeComponentOptions | void;
  componentInstance: Component | void; // component instance
  parent: VNode | void; // component placeholder node

  // strictly internal
  raw: boolean; // contains raw HTML? (server only)
  isStatic: boolean; // hoisted static node
  isRootInsert: boolean; // necessary for enter transition check
  isComment: boolean; // empty comment placeholder?
  isCloned: boolean; // is a cloned node?
  isOnce: boolean; // is a v-once node?
  asyncFactory: Function | void; // async component factory function
  asyncMeta: Object | void;
  isAsyncPlaceholder: boolean;
  ssrContext: Object | void;
  fnContext: Component | void; // real context vm for functional nodes
  fnOptions: ?ComponentOptions; // for SSR caching
  fnScopeId: ?string; // functional scope id support

  constructor (
    tag?: string,
    data?: VNodeData,
    children?: ?Array<VNode>,
    text?: string,
    elm?: Node,
    context?: Component,
    componentOptions?: VNodeComponentOptions,
    asyncFactory?: Function
  ) {
    this.tag = tag
    this.data = data
    this.children = children
    this.text = text
    this.elm = elm
    this.ns = undefined
    this.context = context
    this.fnContext = undefined
    this.fnOptions = undefined
    this.fnScopeId = undefined
    this.key = data && data.key
    this.componentOptions = componentOptions
    this.componentInstance = undefined
    this.parent = undefined
    this.raw = false
    this.isStatic = false
    this.isRootInsert = true
    this.isComment = false
    this.isCloned = false
    this.isOnce = false
    this.asyncFactory = asyncFactory
    this.asyncMeta = undefined
    this.isAsyncPlaceholder = false
  }

  // DEPRECATED: alias for componentInstance for backwards compat.
  /* istanbul ignore next */
  get child (): Component | void {
    return this.componentInstance
  }
}

可以看到VNode中只有对于真实DOM元素的各种属性描述,映射到真实DOM的渲染,并没有其他各种操作DOM的方法。

createElement

Vue中使用createElement方法来进行刚刚提到的VNode的创建。

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其实只是对_createElement方法进行了一层封装,通过封装让_createElement方法变得更加灵活,下面看一下_createElement的实现。

export function _createElement (
  context: Component, // 当前上下文
  tag?: string | Class<Component> | Function | Object, // 标签
  data?: VNodeData, // VNode的数据
  children?: any, // 子节点
  normalizationType?: number // 子节点规范的类型,用于判断render 函数是编译产生的还是用户的行为
): VNode | Array<VNode> {

  // object syntax in v-bind,判断data.is是否存在
  if (isDef(data) && isDef(data.is)) {
    tag = data.is
  }
  // 没有tag就创建一个空节点,所有属性为初始值
  if (!tag) {
    // in case of component :is set to falsy value
    return createEmptyVNode()
  }
  // 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
      )
    }
  }
  // support single function children as default scoped slot
  // 若children[0]是function,则认为是scope slot而不是children
  if (Array.isArray(children) &&
    typeof children[0] === 'function'
  ) {
    data = data || {}
    data.scopedSlots = { default: children[0] }
    children.length = 0
  }
  // 序列化children
  if (normalizationType === ALWAYS_NORMALIZE) {
    children = normalizeChildren(children)
  } else if (normalizationType === SIMPLE_NORMALIZE) {
    children = simpleNormalizeChildren(children)
  }
  // 根据不同的情况创建不同类型的VNode实例并返回
  let vnode, ns
  if (typeof tag === 'string') {
    let Ctor
    ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag)
    if (config.isReservedTag(tag)) {
      // platform built-in elements
      vnode = new VNode(
        config.parsePlatformTagName(tag), data, children,
        undefined, undefined, context
      )
    } else if (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)
  }
  if (Array.isArray(vnode)) {
    return vnode
  } else if (isDef(vnode)) {
    if (isDef(ns)) applyNS(vnode, ns)
    if (isDef(data)) registerDeepBindings(data)
    return vnode
  } else {
    return createEmptyVNode()
  }
}

_createElement先判断若没有tag则调用createEmptyVNode()创建一个empty vnode,empty vnode的数据结构和上面vnode构造函数中的一致。接着判断children[0]是否是个函数,若是,则认为该函数是初始化scoped slot的函数,并放到data中。接下来就是根据不同的情况调用不同的方法进行children的标准化。我们看下children标准化的函数的具体实现:

// 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函数是编译生成的话,则会调用simpleNormalizeChildren进行children的标准化,理论上编译生成的children都已经是 VNode类型的,但这里有一个例外,就是functional component 函数式组件返回的是一个数组而不是一个根节点,所以会通过 Array.prototype.concat方法把整个children数组打平,让它的深度只有一层。

// 2. When the children contains constructs that always generated nested Arrays,
// e.g.