這個(gè)介紹的是 createElement 是怎么創(chuàng)建一個(gè)元素的。接下來還有一篇會(huì)介紹到 createElement 是怎么創(chuàng)建組件的。
- Vue 利用 createElement 方法創(chuàng)建 VNode,定義在 src/core/vdom/crate-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
}
return _createElement(context, tag, data, children, normalizationType)
}
- createElement 方法實(shí)際上是對(duì) _createElement 方法的封裝,它允許傳入的參數(shù)更加靈活,在處理這些參數(shù)后,調(diào)用真正創(chuàng)建 VNode 的函數(shù) _crateElement :
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 個(gè)參數(shù),context 表示 VNode 的上下文環(huán)境,它是 Component 類型;tag 表示標(biāo)簽,它可以是一個(gè)字符串,也可以是一個(gè) Component;data 表示 VNode 的數(shù)據(jù),它是一個(gè) VNodeData 類型,可以在 flow/vnode.js 中找到他的定義;children 表示當(dāng)前 VNode 的子節(jié)點(diǎn),它是任意類型的,接下來需要被規(guī)范為標(biāo)準(zhǔn)的 VNode 數(shù)組; normalizationType 表示子節(jié)點(diǎn)規(guī)范的類型,類型不同規(guī)范的方法也就不一樣,它主要是參考 render 函數(shù)是編譯生成的還是用戶手寫的。
- 因?yàn)?crateElement 函數(shù)的流程略微有點(diǎn)多,接下來就重點(diǎn)分析它的 2 個(gè)重要的路程 —— children 的規(guī)范化以及 VNode 的創(chuàng)建
children 的規(guī)范化
由于 Virtual DOM 實(shí)際上是一個(gè)樹狀結(jié)構(gòu),每一個(gè) VNode 可能會(huì)有若干個(gè)子節(jié)點(diǎn),這些子節(jié)點(diǎn)應(yīng)該也是 VNode 的類型。_createElement 接收的第 4 個(gè)參數(shù) children 是任意類型的,因?yàn)榫托枰阉鼈円?guī)范成 VNode 類型。
這里會(huì)根據(jù) normalizationType 的不同,調(diào)用了 normaliza(children) 和 simpleNormalizeChildren(children) 方法,定義在 src/core/vdom/helpers/normalzie-children.js 中:
// The template compiler attempts to minimize the need for normalization by
// statically analyzing the template at compile time.
//
// For plain HTML markup, normalization can be completely skipped because the
// generated render function is guaranteed to return Array<VNode>. There are
// two cases where extra normalization is needed:
// 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 方法調(diào)用了場(chǎng)景是 render 函數(shù)當(dāng)函數(shù)是編譯生成的。理論上編譯生成的 children 都已經(jīng)是 VNode 類型的,但是這里會(huì)有一些例外的情況,就是 functional component 函數(shù)式組件返回的是一個(gè)數(shù)組而不是一個(gè)根節(jié)點(diǎn),所有會(huì)通過 Array.prototype.concat 方法把整個(gè) children 數(shù)組打平,讓它的深度只有一層。
normalizeChildren 方法的調(diào)用場(chǎng)景有 2 中,一個(gè)場(chǎng)景是 render 函數(shù)是用戶手寫的,當(dāng) children 只有一個(gè)節(jié)點(diǎn)的時(shí)候,Vue 從接口層面允許用戶把 children 寫成基礎(chǔ)類型用來創(chuàng)建單個(gè)簡(jiǎn)單的文本節(jié)點(diǎn),這種情況下回調(diào)用 createTextVNode 創(chuàng)建一個(gè)文本節(jié)點(diǎn)的 VNode;另一個(gè)場(chǎng)景就是當(dāng)編譯 slot、 v-for 的時(shí)候回產(chǎn)生嵌套數(shù)組的情況,回調(diào)用 normalizeArrayChildren 方法,先來看一下它是怎么實(shí)現(xiàn)的:
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 個(gè)參數(shù),children 表示要規(guī)范的子節(jié)點(diǎn),nestedIndex 表示嵌套的索引,因?yàn)閱蝹€(gè) child 可能是一個(gè)數(shù)組類型。normalizeArrayCHildren 主要的邏輯就是遍歷 children,獲得單個(gè)節(jié)點(diǎn) c,然后對(duì) c 的類型判斷
- 如果是一個(gè)數(shù)組類型,則遞歸調(diào)用 normalizeArrayChildren;
- 如果是基礎(chǔ)類型,則通過 createTextVNode 方法轉(zhuǎn)換成 VNode 類型;否則就已經(jīng)是 VNode 類型了
- 如果 children 是一個(gè)列表并且列表還存在嵌套的情況,則根據(jù) nestedIndex 去更新它的 key。
- 還有需要注意的是,在遍歷過程中,對(duì)著 3 中情況都做了以下處理: 若果存在兩個(gè)連續(xù)的 text 節(jié)點(diǎn),會(huì)把他們合并成一個(gè) text 節(jié)點(diǎn)。
- 經(jīng)過對(duì) children 的規(guī)范化,children 變成了一個(gè)類型為 VNode 的 Array。
VNode 的創(chuàng)建
- 接著回到 createElement 函數(shù),規(guī)范化 children 后,接下來會(huì)去創(chuàng)建一個(gè) VNode 的實(shí)例, 文件在 vdom/create-element.js 中
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()
}
- 這里先對(duì) tag 做判斷,如果是 string 類型,則接著判斷如果是內(nèi)置的一些節(jié)點(diǎn),則直接創(chuàng)建一個(gè)普通 VNode,如果是為已注冊(cè)的組件名,則通過 createComponent 創(chuàng)建一個(gè)組件類型的 VNode,否則創(chuàng)建一個(gè)未知的標(biāo)簽的 VNode。如果是 tag 一個(gè) Component 類型,則直接調(diào)用 createComponent 創(chuàng)建一個(gè)組件類型的 VNode 節(jié)點(diǎn)。
上面也大致了解了 createElement 創(chuàng)建 VNode 的過程。每個(gè) VNode 有 children,children 每個(gè)元素也是一個(gè) VNode,這樣就形成了一個(gè) VNode Tree,它很好的描述了 DOM Tree。
mountComponent 函數(shù)的過程,已經(jīng)知道 vm._render 是如何創(chuàng)建一個(gè) VNode,接下來就是要把這個(gè) VNode 渲染成一個(gè)真實(shí)的 DOM 并且渲染出來,這個(gè)過程是通過 vm._update 完成的,你可以看我下一篇關(guān)于 vm._update 的文章。