Virtual DOM
Virtual DOM
這個概念相信大部分人都不會陌生,它產(chǎn)生的前提是瀏覽器中的DOM是很“昂貴"的,為了更直觀的感受,我們可以簡單的把一個簡單的div
元素的屬性都打印出來,如圖所示:
可以看到,真正的DOM元素是非常龐大的,因為瀏覽器的標(biāo)準(zhǔn)就把DOM設(shè)計的非常復(fù)雜。當(dāng)我們頻繁的去做DOM更新,會產(chǎn)生一定的性能問題。
而Virtual DOM
就是用一個原生的JS對象去描述一個DOM節(jié)點,所以它比創(chuàng)建一個DOM的代價要小很多。在Vue.js中,Virtual DOM
是用VNode
這么一個Class
去描述,它是定義在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
}
}
實際上Vue.js中Virtual DOM
是借鑒了一個開源庫snabbdom 的實現(xiàn),然后加入了一些Vue.js特色的東西。這個庫更加簡單和純粹。
其實VNode
是對真實DOM的一種抽象描述,它的核心定義無非就幾個關(guān)鍵屬性,標(biāo)簽名、數(shù)據(jù)、子節(jié)點、鍵值等,其它屬性都是都是用來擴展VNode
的靈活性以及實現(xiàn)一些特殊feature
的。由于VNode
只是用來映射到真實DOM的渲染,不需要包含操作DOM的方法,因此它是非常輕量和簡單的。
Virtual DOM
除了它的數(shù)據(jù)結(jié)構(gòu)的定義,映射到真實的DOM實際上要經(jīng)歷VNode
的create、diff、patch
等過程。那么在Vue.js中,VNode
的create
是通過之前提到的createElement
方法創(chuàng)建的。
createElement
Vue.js利用createElement
方法創(chuàng)建VNode
,它定義在src/core/vdom/create-elemenet.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
方法實際上是對_createElement
方法的封裝,它允許傳入的參數(shù)更加靈活,在處理這些參數(shù)后,調(diào)用真正創(chuàng)建VNode
的函數(shù)_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個參數(shù),context
表示VNode
的上下文環(huán)境,它是Component
類型;tag
表示標(biāo)簽,它可以是一個字符串,也可以是一個Component
;data
表示VNode
的數(shù)據(jù),它是一個VNodeData
類型,可以在flow/vnode.js
中找到它的定義,這里先不展開說;children
表示當(dāng)前VNode
的子節(jié)點,它是任意類型的,它接下來需要被規(guī)范為標(biāo)準(zhǔn)的VNode
數(shù)組;normalizationType
表示子節(jié)點規(guī)范的類型,類型不同規(guī)范的方法也就不一樣,它主要是參考 render
函數(shù)是編譯生成的還是用戶手寫的。
createElement
函數(shù)的流程略微有點多,我們接下來主要分析2個重點的流程——children
的規(guī)范化以及VNode
的創(chuàng)建。
children的規(guī)范化
由于Virtual DOM實際上是一個樹狀結(jié)構(gòu),每一個VNode
可能會有若干個子節(jié)點,這些子節(jié)點應(yīng)該也是VNode
的類型。_createElement
接收的第 4個參數(shù)children
是任意類型的,因此我們需要把它們規(guī)范成VNode
類型。
這里根據(jù)normalizationType
的不同,調(diào)用了normalizeChildren(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)用場景是render
函數(shù)是編譯生成的。理論上編譯生成的children
都已經(jīng)是VNode
類型的,但這里有一個例外,就是functional component
函數(shù)式組件返回的是一個數(shù)組而不是一個根節(jié)點,所以會通過Array.prototype.concat
方法把整個children
數(shù)組打平,讓它的深度只有一層。
normalizeChildren
方法的調(diào)用場景有2種,一個場景是render
函數(shù)是用戶手寫的,當(dāng)children
只有一個節(jié)點的時候,Vue.js從接口層面允許用戶把children
寫成基礎(chǔ)類型用來創(chuàng)建單個簡單的文本節(jié)點,這種情況會調(diào)用createTextVNode
創(chuàng)建一個文本節(jié)點的VNode
;另一個場景是當(dāng)編譯slot
、v-for
的時候會產(chǎn)生嵌套數(shù)組的情況,會調(diào)用normalizeArrayChildren
方法,接下來看一下它的實現(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個參數(shù),children
表示要規(guī)范的子節(jié)點,nestedIndex
表示嵌套的索引,因為單個child
可能是一個數(shù)組類型。 normalizeArrayChildren
主要的邏輯就是遍歷children
,獲得單個節(jié)點c
,然后對c
的類型判斷,如果是一個數(shù)組類型,則遞歸調(diào)用normalizeArrayChildren
; 如果是基礎(chǔ)類型,則通過createTextVNode
方法轉(zhuǎn)換成VNode
類型;否則就已經(jīng)是VNode
類型了,如果children
是一個列表并且列表還存在嵌套的情況,則根據(jù)nestedIndex
去更新它的key
。這里需要注意一點,在遍歷的過程中,對這3種情況都做了如下處理:如果存在兩個連續(xù)的text
節(jié)點,會把它們合并成一個text
節(jié)點。
經(jīng)過對children
的規(guī)范化,children
變成了一個類型為VNode
的Array
。
VNode的創(chuàng)建
回到createElement
函數(shù),規(guī)范化children
后,接下來會去創(chuàng)建一個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)
}
這里先對tag
做判斷,如果是string
類型,則接著判斷如果是內(nèi)置的一些節(jié)點,則直接創(chuàng)建一個普通VNode
,如果是為已注冊的組件名,則通過createComponent
創(chuàng)建一個組件類型的VNode
,否則創(chuàng)建一個未知的標(biāo)簽的VNode
。 如果是tag
一個Component
類型,則直接調(diào)用createComponent
創(chuàng)建一個組件類型的VNode
節(jié)點。對于createComponent
創(chuàng)建組件類型的VNode
的過程,本質(zhì)上它還是返回了一個VNode
。
那么至此,我們大致了解了createElement
創(chuàng)建VNode
的過程,每個VNode
有children
,children
每個元素也是一個VNode
,這樣就形成了一個VNode Tree
,它很好的描述了我們的 DOM Tree
。
回到mountComponent
函數(shù)的過程,我們已經(jīng)知道vm._render
是如何創(chuàng)建了一個VNode
,接下來就是要把這個VNode
渲染成一個真實的DOM并渲染出來,這個過程是通過vm._update
完成的,接下來分析一下這個過程。
update
Vue
的_update
是實例的一個私有方法,它被調(diào)用的時機有2個,一個是首次渲染,一個是數(shù)據(jù)更新的時候。_update
方法的作用是把VNode
渲染成真實的DOM,它的定義在src/core/instance/lifecycle.js
中:
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
const vm: Component = this
const prevEl = vm.$el
const prevVnode = vm._vnode
const prevActiveInstance = activeInstance
activeInstance = vm
vm._vnode = vnode
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
if (!prevVnode) {
// initial render
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode)
}
activeInstance = prevActiveInstance
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null
}
if (vm.$el) {
vm.$el.__vue__ = vm
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el
}
// updated hook is called by the scheduler to ensure that children are
// updated in a parent's updated hook.
}
_update
的核心就是調(diào)用vm.__patch__
方法,這個方法實際上在不同的平臺,比如web和weex上的定義是不一樣的,因此在web平臺中它的定義在src/platforms/web/runtime/index.js
中:
Vue.prototype.__patch__ = inBrowser ? patch : noop
可以看到,甚至在web平臺上,是否是服務(wù)端渲染也會對這個方法產(chǎn)生影響。因為在服務(wù)端渲染中,沒有真實的瀏覽器DOM環(huán)境,所以不需要把VNode
最終轉(zhuǎn)換成DOM,因此是一個空函數(shù),而在瀏覽器端渲染中,它指向了patch
方法,它的定義在src/platforms/web/runtime/patch.js
中:
import * as nodeOps from 'web/runtime/node-ops'
import { createPatchFunction } from 'core/vdom/patch'
import baseModules from 'core/vdom/modules/index'
import platformModules from 'web/runtime/modules/index'
// the directive module should be applied last, after all
// built-in modules have been applied.
const modules = platformModules.concat(baseModules)
export const patch: Function = createPatchFunction({ nodeOps, modules })
該方法的定義是調(diào)用createPatchFunction
方法的返回值,這里傳入了一個對象,包含nodeOps
參數(shù)和modules
參數(shù)。其中,nodeOps
封裝了一系列DOM操作的方法,modules
定義了一些模塊的鉤子函數(shù)的實現(xiàn),來看一下createPatchFunction
的實現(xiàn),它定義在src/core/vdom/patch.js
中:
const hooks = ['create', 'activate', 'update', 'remove', 'destroy']
export function createPatchFunction (backend) {
let i, j
const cbs = {}
const { modules, nodeOps } = backend
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = []
for (j = 0; j < modules.length; ++j) {
if (isDef(modules[j][hooks[i]])) {
cbs[hooks[i]].push(modules[j][hooks[i]])
}
}
}
// ...
return function patch (oldVnode, vnode, hydrating, removeOnly) {
if (isUndef(vnode)) {
if (isDef(oldVnode)) invokeDestroyHook(oldVnode)
return
}
let isInitialPatch = false
const insertedVnodeQueue = []
if (isUndef(oldVnode)) {
// empty mount (likely as component), create new root element
isInitialPatch = true
createElm(vnode, insertedVnodeQueue)
} else {
const isRealElement = isDef(oldVnode.nodeType)
if (!isRealElement && sameVnode(oldVnode, vnode)) {
// patch existing root node
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly)
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) {
oldVnode.removeAttribute(SSR_ATTR)
hydrating = true
}
if (isTrue(hydrating)) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true)
return oldVnode
} else if (process.env.NODE_ENV !== 'production') {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
)
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode)
}
// replacing existing element
const oldElm = oldVnode.elm
const parentElm = nodeOps.parentNode(oldElm)
// create new node
createElm(
vnode,
insertedVnodeQueue,
// extremely rare edge case: do not insert if old element is in a
// leaving transition. Only happens when combining transition +
// keep-alive + HOCs. (#4590)
oldElm._leaveCb ? null : parentElm,
nodeOps.nextSibling(oldElm)
)
// update parent placeholder node element, recursively
if (isDef(vnode.parent)) {
let ancestor = vnode.parent
const patchable = isPatchable(vnode)
while (ancestor) {
for (let i = 0; i < cbs.destroy.length; ++i) {
cbs.destroy[i](ancestor)
}
ancestor.elm = vnode.elm
if (patchable) {
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, ancestor)
}
// #6513
// invoke insert hooks that may have been merged by create hooks.
// e.g. for directives that uses the "inserted" hook.
const insert = ancestor.data.hook.insert
if (insert.merged) {
// start at index 1 to avoid re-invoking component mounted hook
for (let i = 1; i < insert.fns.length; i++) {
insert.fns[i]()
}
}
} else {
registerRef(ancestor)
}
ancestor = ancestor.parent
}
}
// destroy old node
if (isDef(parentElm)) {
removeVnodes(parentElm, [oldVnode], 0, 0)
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode)
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
return vnode.elm
}
}
createPatchFunction
內(nèi)部定義了一系列的輔助方法,最終返回了一個patch
方法,這個方法就賦值給了vm._update
函數(shù)里調(diào)用的vm.__patch__
。
在介紹patch
的方法實現(xiàn)之前,我們可以思考一下為何Vue.js源碼繞了這么一大圈,把相關(guān)代碼分散到各個目錄。因為patch
是平臺相關(guān)的,在Web和Weex環(huán)境,它們把虛擬DOM映射到“平臺DOM”的方法是不同的,并且對“DOM”包括的屬性模塊創(chuàng)建和更新也不盡相同。因此每個平臺都有各自的nodeOps
和modules
,它們的代碼需要托管在src/platforms
這個大目錄下。
而不同平臺的patch
的主要邏輯部分是相同的,所以這部分公共的部分托管在core
這個大目錄下。差異化部分只需要通過參數(shù)來區(qū)別,這里用到了一個函數(shù)柯里化的技巧,通過createPatchFunction
把差異化參數(shù)提前固化,這樣不用每次調(diào)用patch
的時候都傳遞nodeOps
和modules
了,這種編程技巧也非常值得學(xué)習(xí)。
在這里,nodeOps
表示對“平臺 DOM”的一些操作方法,modules
表示平臺的一些模塊,它們會在整個patch
過程的不同階段執(zhí)行相應(yīng)的鉤子函數(shù)。
回到patch
方法本身,它接收4個參數(shù),oldVnode
表示舊的VNode
節(jié)點,它也可以不存在或者是一個DOM對象;vnode
表示執(zhí)行_render
后返回的VNode
的節(jié)點;hydrating
表示是否是服務(wù)端渲染;removeOnly
是給transition-group
用的。
先來回顧我們的例子:
var app = new Vue({
el: '#app',
render: function (createElement) {
return createElement('div', {
attrs: {
id: 'app'
},
}, this.message)
},
data: {
message: 'Hello Vue!'
}
})
然后我們在vm._update
的方法里是這么調(diào)用patch
方法的:
// initial render
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
結(jié)合我們的例子,我們的場景是首次渲染,所以在執(zhí)行patch
函數(shù)的時候,傳入的vm.$el
對應(yīng)的是例子中id
為app
的DOM對象,這個也就是我們在index.html
模板中寫的<div id="app">
, vm.$el
的賦值是在之前mountComponent
函數(shù)做的,vnode
對應(yīng)的是調(diào)用render
函數(shù)的返回值,hydrating
在非服務(wù)端渲染情況下為false
,removeOnly
為false
。
確定了這些入?yún)⒑螅覀兓氐?code>patch函數(shù)的執(zhí)行過程,看幾個關(guān)鍵步驟。
const isRealElement = isDef(oldVnode.nodeType)
if (!isRealElement && sameVnode(oldVnode, vnode)) {
// patch existing root node
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly)
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) {
oldVnode.removeAttribute(SSR_ATTR)
hydrating = true
}
if (isTrue(hydrating)) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true)
return oldVnode
} else if (process.env.NODE_ENV !== 'production') {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
)
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode)
}
// replacing existing element
const oldElm = oldVnode.elm
const parentElm = nodeOps.parentNode(oldElm)
// create new node
createElm(
vnode,
insertedVnodeQueue,
// extremely rare edge case: do not insert if old element is in a
// leaving transition. Only happens when combining transition +
// keep-alive + HOCs. (#4590)
oldElm._leaveCb ? null : parentElm,
nodeOps.nextSibling(oldElm)
)
}
由于我們傳入的oldVnode
實際上是一個DOM container
,所以isRealElement
為true
,接下來又通過emptyNodeAt
方法把oldVnode
轉(zhuǎn)換成VNode
對象,然后再調(diào)用createElm
方法,這個方法在這里非常重要,來看一下它的實現(xiàn):
function createElm (
vnode,
insertedVnodeQueue,
parentElm,
refElm,
nested,
ownerArray,
index
) {
if (isDef(vnode.elm) && isDef(ownerArray)) {
// This vnode was used in a previous render!
// now it's used as a new node, overwriting its elm would cause
// potential patch errors down the road when it's used as an insertion
// reference node. Instead, we clone the node on-demand before creating
// associated DOM element for it.
vnode = ownerArray[index] = cloneVNode(vnode)
}
vnode.isRootInsert = !nested // for transition enter check
if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
return
}
const data = vnode.data
const children = vnode.children
const tag = vnode.tag
if (isDef(tag)) {
if (process.env.NODE_ENV !== 'production') {
if (data && data.pre) {
creatingElmInVPre++
}
if (isUnknownElement(vnode, creatingElmInVPre)) {
warn(
'Unknown custom element: <' + tag + '> - did you ' +
'register the component correctly? For recursive components, ' +
'make sure to provide the "name" option.',
vnode.context
)
}
}
vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag, vnode)
setScope(vnode)
/* istanbul ignore if */
if (__WEEX__) {
// ...
} else {
createChildren(vnode, children, insertedVnodeQueue)
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
insert(parentElm, vnode.elm, refElm)
}
if (process.env.NODE_ENV !== 'production' && data && data.pre) {
creatingElmInVPre--
}
} else if (isTrue(vnode.isComment)) {
vnode.elm = nodeOps.createComment(vnode.text)
insert(parentElm, vnode.elm, refElm)
} else {
vnode.elm = nodeOps.createTextNode(vnode.text)
insert(parentElm, vnode.elm, refElm)
}
}
createElm
的作用是通過虛擬節(jié)點創(chuàng)建真實的DOM并插入到它的父節(jié)點中。 我們來看一下它的一些關(guān)鍵邏輯,createComponent
方法目的是嘗試創(chuàng)建子組件,在當(dāng)前這個case
下它的返回值為false
;接下來判斷vnode
是否包含tag
,如果包含,先簡單對tag
的合法性在非生產(chǎn)環(huán)境下做校驗,看是否是一個合法標(biāo)簽;然后再去調(diào)用平臺DOM的操作去創(chuàng)建一個占位符元素。
vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag, vnode)
接下來調(diào)用createChildren
方法去創(chuàng)建子元素:
createChildren(vnode, children, insertedVnodeQueue)
function createChildren (vnode, children, insertedVnodeQueue) {
if (Array.isArray(children)) {
if (process.env.NODE_ENV !== 'production') {
checkDuplicateKeys(children)
}
for (let i = 0; i < children.length; ++i) {
createElm(children[i], insertedVnodeQueue, vnode.elm, null, true, children, i)
}
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text)))
}
}
createChildren
的邏輯很簡單,實際上是遍歷子虛擬節(jié)點,遞歸調(diào)用createElm
,這是一種常用的深度優(yōu)先的遍歷算法,這里要注意的一點是在遍歷過程中會把vnode.elm
作為父容器的DOM節(jié)點占位符傳入。
接著再調(diào)用invokeCreateHooks
方法執(zhí)行所有的create
的鉤子并把vnodev push
到insertedVnodeQueue
中。
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
function invokeCreateHooks (vnode, insertedVnodeQueue) {
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode)
}
i = vnode.data.hook // Reuse variable
if (isDef(i)) {
if (isDef(i.create)) i.create(emptyNode, vnode)
if (isDef(i.insert)) insertedVnodeQueue.push(vnode)
}
}
最后調(diào)用insert
方法把DOM插入到父節(jié)點中,因為是遞歸調(diào)用,子元素會優(yōu)先調(diào)用insert
,所以整個vnode
樹節(jié)點的插入順序是先子后父。來看一下insert
方法,它的定義在src/core/vdom/patch.js
上。
insert(parentElm, vnode.elm, refElm)
function insert (parent, elm, ref) {
if (isDef(parent)) {
if (isDef(ref)) {
if (ref.parentNode === parent) {
nodeOps.insertBefore(parent, elm, ref)
}
} else {
nodeOps.appendChild(parent, elm)
}
}
}
insert
邏輯很簡單,調(diào)用一些nodeOps
把子節(jié)點插入到父節(jié)點中,這些輔助方法定義在src/platforms/web/runtime/node-ops.js
中:
export function insertBefore (parentNode: Node, newNode: Node, referenceNode: Node) {
parentNode.insertBefore(newNode, referenceNode)
}
export function appendChild (node: Node, child: Node) {
node.appendChild(child)
}
其實就是調(diào)用原生DOM的API進行DOM操作。
在createElm
過程中,如果vnode
節(jié)點不包含tag
,則它有可能是一個注釋或者純文本節(jié)點,可以直接插入到父元素中。在我們這個例子中,最內(nèi)層就是一個文本 vnode
,它的text
值取的就是之前的this.message
的值Hello Vue!
。
再回到patch
方法,首次渲染我們調(diào)用了createElm
方法,這里傳入的parentElm
是oldVnode.elm
的父元素,在我們的例子是id
為#app div
的父元素,也就是body
;實際上整個過程就是遞歸創(chuàng)建了一個完整的DOM樹并插入到body
上。
最后,我們根據(jù)之前遞歸createElm
生成的vnode
插入順序隊列,執(zhí)行相關(guān)的insert
鉤子函數(shù)。
總結(jié)
那么至此我們從主線上把模板和數(shù)據(jù)如何渲染成最終的DOM的過程分析完畢了,我們可以通過下圖更直觀地看到從初始化Vue
到最終渲染的整個過程。