Open chenfaxiang opened 6 years ago
Vue.js 利用 createElement 方法创建 VNode,它定义在 /src/core/vdom/create-element.js
中:
// 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
}
// 利用 _createElement 创建 VNode
return _createElement(context, tag, data, children, normalizationType)
}
这里 createElement
实际上是对 _createElement
的封装,处理参数后,调用 _createElement
创建真正的 VNode;而 _createElement
:
export function _createElement (
context: Component,
tag?: string | Class<Component> | Function | Object,
data?: VNodeData,
children?: any,
normalizationType?: number
): VNode | Array<VNode> {
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()
}
// 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()
}
// 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
if (Array.isArray(children) &&
typeof children[0] === 'function'
) {
data = data || {}
data.scopedSlots = { default: children[0] }
children.length = 0
}
if (normalizationType === ALWAYS_NORMALIZE) {
children = normalizeChildren(children)
} else if (normalizationType === SIMPLE_NORMALIZE) {
children = simpleNormalizeChildren(children)
}
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
有5个参数,context
表示 VNode 的上下文环境,tag
表示标签,data
表示 VNode 的数据,childen
表示当前 VNode 的子节点,normalizationType
表示子节点规范类型,类型不同规范的方法也就不同,主要是参考 render
函数是编译生成的还是用户手写的。而流程中两个重点分别是 children
的规范化以及 VNode
的创建。
由于 Virtual DOM 是一个树状结构,灭一个 VNode 可能会有若干子节点,而这些子节点也应该是 VNode 类型;在 _createElement
中根据类型不同调用了两个不同的函数:
if (normalizationType === ALWAYS_NORMALIZE) {
children = normalizeChildren(children)
} else if (normalizationType === SIMPLE_NORMALIZE) {
children = simpleNormalizeChildren(children)
}
normalizeChildren(children)
和 simpleNormalizeChildren(children)
都定义在 /src/core/vdom/helpers/normalize-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.
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
}
// 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
}
simpleNormalizeChildren
的调用场景是 render
函数当函数是编译生成的,理论上编译生成的 children
都已经是 VNode 类型的,但例外的是, functional component
函数式组件返回的是一个数组而不是根节点,所以会通过 Array.prototype.concat
方法把整个 children
数组连接,让它的深度只有一层;
normalizeChildren
的调用场景有两个:一个是 render
函数是用户手写的,当 children
节点只有一个的时候,这种情况会调用 createTextVNode
创建一个文本节点的 VNode;另一个场景是当编译 slot
、v-for
的时候会产生嵌套数组的情况,会调用 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
}
normalizeArrayChildren
接收两个参数:children
表示要规范的子节点,nestedIndex
表示嵌套的索引,因为单个 child 可能是一个数组类型;这里的主要逻辑就是遍历 children
,获得单个节点 c
并对其类型进行判断,如果是数组则递归调用此函数,如果是基础类型,则通过 createTextVNode
方法转换成 VNode 类型,否则就是 VNode 类型了;如果 children
是一个列表并且列表还存在嵌套的情况,则根据 nestedIndex
去更新它的 key
。这里需要注意一点,在遍历的过程中,对这 3 种情况都做了如下处理:如果存在两个连续的 text 节点,会把它们合并成一个 text 节点;最后,children
变成了一个类型为 VNode 的 Array
。
回到 createElement
函数,规范化 children
后,接下来会去创建一个 VNode 的实例:
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)
}
这里就是对 tag
类型和内置的一些节点的值进行判断来创建 VNode。
前面学习了 createElement
创建 VNode 的过程,每个 VNode 有 children
,children
每个元素也是一个 VNode,这样就形成了一个 VNode Tree,它很好的描述了我们的 DOM Tree。
最后回到 mountComponent
函数的过程,我们已经知道 vm._render
是如何创建了一个 VNode,接下来就是要把这个 VNode 渲染成一个真实的 DOM 并渲染出来,下面将是 vm._update
。
Virtual DOM
在学习 VUE 的过程中对虚拟 DOM 这个概念已经是耳熟能详,但是什么是真正的虚拟 DOM 呢?下面跟着源代码走一波,看一看究竟是何方神圣。 我们平常接触的 div 等元素只要创建,那么它的所有属性就是一个庞大的集合,这些属性究竟有多庞大?如下: 一个真正的 DOM,浏览器的标准就把它设计的非常复杂,当平凡的去更新 DOM 的时候就会产生一定的性能问题(虽然平时使用也没有怎么发现,亲身体验当处理几百上千甚至更多的下拉列表时就出现了卡顿问题了)
Virtual DOM一探究竟
在
Vue
中 Virtual DOM 就是用一个原生的 DOM 节点,所以它比创建一个 DOM 的代价要小很多;Virtual DOM 是用VNode
这么一个 Class 去描述,它是定义在/src/core/vdom/vnode.js
中的,如下:它是对真实 DOM 的一种抽象描述,这里的几个核心属性:标签名、数据、子节点、键值等,其它属性都是用来扩展 VNode 的灵活性以及特殊的 feature 的;由于 VNode 只是用来映射到真实 DOM 的渲染,不需要包含操作 DOM 的方法,因此它非常轻量和简单。 Virtual DOM 除了它的数据结构的定义,映射到真实的 DOM 实际上要经历 VNode 的 create、diff、patch 等过程。那么在 Vue.js 中,VNode 的 create 是通过之前提到的 createElement 方法创建的,下面看看 createElement 的实现。