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. <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
}

当children只有一个节点的时候,Vue允许children是简单类型变量,比如String,这时候会调用createTextVNode创建一个文本节点。当用户使用slot、v-for、functions或jsx的时候有可能会产生children嵌套的情况,这是会调用normalizeArrayChildren方法进行arrayChildren的规范化。

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
}

normalizeArrayChildren接收2个参数,children表示要规范的子节点,nestedIndex表示嵌套的索引,因为单个child可能是一个数组类型。normalizeArrayChildren主要的逻辑就是遍历children,获得单个节点c,然后对c的类型判断,如果是一个数组类型,则递归调用normalizeArrayChildren;如果是基础类型,则通过createTextVNode方法转换成VNode类型;否则就已经是VNode类型了,如果children是一个列表并且列表还存在嵌套的情况,则根据nestedIndex去更新它的key。这里需要注意一点,在遍历的过程中,对这 3 种情况都做了如下处理:如果存在两个连续的text节点,会把它们合并成一个text 节点。

在经过一个一系列的规范化操作之后,VNode中的children变成为Array类型。接下来就是根据不同的情况实例化不同的VNode,这里先对tag进行判断,如果是string类型,则接着判断如果是内置的一些节点,则直接创建一个普通VNode,如果是已注册的组件名,则通过createComponent创建一个组件类型的VNode,否则创建一个未知的标签的VNode。如果是tag一个Component类型,则直接调用createComponent创建一个组件类型的 VNode 节点。

总结

我们在使用createElement创建template的时候其实是创建了一个VNode,VNode是对真实DOM的一种抽象,里面包含了真实DOM的各种映射。createElement会根据不同的情况对children进行相应的标准化,最终产生一个VNode组成的children数组,最后产生一个对应的VNode并返回。

猜你喜欢

转载自blog.csdn.net/qq_34179086/article/details/88086376