【vue2源码学习】— createElement

文章详细介绍了Vue.js中通过`createElement`创建虚拟DOM节点的过程,包括children的规范化处理,如`simpleNormalizeChildren`和`normalizeChildren`函数的作用,以及如何处理不同类型的子节点,如文本节点、组件和嵌套数组。此外,还提到了VNode的上下文环境、数据和标签的处理。

上一篇

上篇文章我们知道了vue通过实例调用_render函数
最终通过createElement方法创建 VNode
接下来我们来看看createElement怎么创建虚拟dom的
//src/core/vdom/create-element.js
export function createElement (...省略){
	...对参数做一些处理省略
	//normalizationType如果是用户手写的render会被处理为2
  return _createElement(context, tag, data, children, normalizationType)
}
createElement 方法封装了 _createElement,
在处理参数后,再调用_createElement创建 VNode 
// _createElement和createElement在同一个文件
export function _createElement (
  context: Component, //  VNode 的上下文环境
  tag?: string | Class<Component> | Function | Object,
  data?: VNodeData, // VNode 的数据
  children?: any, //当前 VNode 的子节点
  normalizationType?: number // 子节点规范的类型通过render是编译生成的还是用户手写的判定
): VNode | Array<VNode> {
	if (isDef(data) && isDef((data: any).__ob__)) {
		...
	  return createEmptyVNode()
	}
	// object syntax in v-bind
	if (isDef(data) && isDef(data.is)) {
	  tag = data.is
	}
	if (!tag) {
	  // in case of component :is set to falsy value
	  return createEmptyVNode()
	}
	...
	// support single function children as default scoped slot
    if (Array.isArray(children) &&
      typeof children[0] === 'function'
    ) {
      data = data || {}
      data.scopedSlots = { default: children[0] }
      children.length = 0
    }
    // 因为children是any类型所以要通过判定normalizationType规范化
    if (normalizationType === ALWAYS_NORMALIZE) {
      children = normalizeChildren(children)
    } else if (normalizationType === SIMPLE_NORMALIZE) {
      children = simpleNormalizeChildren(children)
    }
  // 经过对 children 的规范化,children 变成了一个类型为 VNode 的 Array。

  // 这里先对 tag 做判断,如果是 string 类型,
  // 则接着判断如果是内置的一些节点,则直接创建一个普通 VNode,
  // 如果是为已注册的组件名,
  // 则通过 createComponent 创建一个组件类型的 VNode,
  // 否则创建一个未知标签的 VNode。 如果tag是一个 Component 类型,
  // 则直接调用 createComponent 创建一个组件类型的 VNode 节点。
  // 对于 createComponent 创建组件类型的 VNode 的过程,
  // 本质上它还是返回了一个 VNode。
  let vnode, ns
  if (typeof tag === 'string') {
    let Ctor
    ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag)
    if (config.isReservedTag(tag)) {
     ...
      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)
  }
  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 函数内容有点多
但是重点主要是两个
1.children 的规范化
2.生成虚拟node
//children 的规范化 src/core/vdom/helpers/normalzie-children.js
// 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.

// simpleNormalizeChildren 方法调用场景是 render 函数是编译生成的。
// 根据注释函数式组件可能返回的是一个数组而不是一个根节点
// 比如:
// render: function(c) {
//   return  [['1', '2'], '3']
// }
// 所以会通过 Array.prototype.concat 方法把整个 children 数组打平,
// 让它的深度只有一层。
export function simpleNormalizeChildren (children: any) {
  for (let i = 0; i < children.length; i++) {
  // children至少是二维数组,会展平children
    if (Array.isArray(children[i])) {
    // 展平后就得到['1', '2', '3']
      return Array.prototype.concat.apply([], children)
    }
  }
  return 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.

// normalizeChildren 方法的调用场景有 2 种,
// 一个场景是 render 函数是用户手写的,当 children 只有一个节点的时候,
// Vue.js 从接口层面允许用户把 children 写成基础类型用来创建单个简单的文本节点,
// 这种情况会调用 createTextVNode 创建一个文本节点的 VNode;
// 另一个场景是当编译 slot、v-for 的时候会产生嵌套数组的情况,
// 会调用 normalizeArrayChildren 方法
// isPrimitive是判定是不是原始简单类型像字符串,数字这些
export function normalizeChildren (children: any): ?Array<VNode> {
  return isPrimitive(children)
    ? [createTextVNode(children)]
    : Array.isArray(children)
      ? normalizeArrayChildren(children)
      : undefined
}
// normalizeArrayChildren函数 src/core/vdom/helpers/normalzie-children.js
// normalizeArrayChildren 接收 2 个参数,
// children 表示要规范的子节点,nestedIndex 表示嵌套的索引,
// 因为单个 child 可能是一个数组类型。 
// normalizeArrayChildren 主要的逻辑就是遍历 children,获得单个节点 c,
// 然后对 c 的类型判断,如果是一个数组类型,则递归调用 normalizeArrayChildren; 
// 如果是基础类型,则通过 createTextVNode 方法转换成 VNode 类型;
// 否则就已经是 VNode 类型了,如果 children 是一个列表并且列表还存在嵌套的情况,
// 则根据 nestedIndex 去更新它的 key。这里需要注意一点,在遍历的过程中,
// 对这 3 种情况都做了如下处理:
// 如果存在两个连续的 text 节点,会把它们合并成一个 text 节点。
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
        // 文本类型进行合并, 下面还有类似的操作
        // 处理这种 children ['1', ['2']], 第一轮过循环后res为['1']
        // c递归后得到['2']的vnode数组
        if (isTextNode(c[0]) && isTextNode(last)) {
          res[lastIndex] = createTextVNode(last.text + (c[0]: any).text)
          c.shift()
          // 经过处理得到 res 为 ['12'] c 为 []
        }
        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 {
        //嵌套的节点没有定义key用nestedIndex给它设置key
        // 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
}

函数组件文档
下一篇

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值