Virtual DOM
Virtual DOM
這個(gè)概念相信大部分人都不會(huì)陌生,它產(chǎn)生的前提是瀏覽器中的DOM是很“昂貴"的监右,為了更直觀的感受抖僵,我們可以簡(jiǎn)單的把一個(gè)簡(jiǎn)單的div
元素的屬性都打印出來(lái)反番,如圖所示:
可以看到灭红,真正的DOM元素是非常龐大的狗唉,因?yàn)闉g覽器的標(biāo)準(zhǔn)就把DOM設(shè)計(jì)的非常復(fù)雜初烘。當(dāng)我們頻繁的去做DOM更新,會(huì)產(chǎn)生一定的性能問(wèn)題。
而Virtual DOM
就是用一個(gè)原生的JS對(duì)象去描述一個(gè)DOM節(jié)點(diǎn)肾筐,所以它比創(chuàng)建一個(gè)DOM的代價(jià)要小很多哆料。在Vue.js中,Virtual DOM
是用VNode
這么一個(gè)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
}
}
實(shí)際上Vue.js中Virtual DOM
是借鑒了一個(gè)開(kāi)源庫(kù)snabbdom 的實(shí)現(xiàn),然后加入了一些Vue.js特色的東西唬渗。這個(gè)庫(kù)更加簡(jiǎn)單和純粹典阵。
其實(shí)VNode
是對(duì)真實(shí)DOM的一種抽象描述,它的核心定義無(wú)非就幾個(gè)關(guān)鍵屬性镊逝,標(biāo)簽名壮啊、數(shù)據(jù)、子節(jié)點(diǎn)撑蒜、鍵值等歹啼,其它屬性都是都是用來(lái)擴(kuò)展VNode
的靈活性以及實(shí)現(xiàn)一些特殊feature
的。由于VNode
只是用來(lái)映射到真實(shí)DOM的渲染座菠,不需要包含操作DOM的方法狸眼,因此它是非常輕量和簡(jiǎn)單的。
Virtual DOM
除了它的數(shù)據(jù)結(jié)構(gòu)的定義浴滴,映射到真實(shí)的DOM實(shí)際上要經(jīng)歷VNode
的create拓萌、diff、patch
等過(guò)程巡莹。那么在Vue.js中司志,VNode
的create
是通過(guò)之前提到的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
方法實(shí)際上是對(duì)_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個(gè)參數(shù)激才,context
表示VNode
的上下文環(huán)境,它是Component
類型额嘿;tag
表示標(biāo)簽瘸恼,它可以是一個(gè)字符串,也可以是一個(gè)Component
册养;data
表示VNode
的數(shù)據(jù)东帅,它是一個(gè)VNodeData
類型,可以在flow/vnode.js
中找到它的定義球拦,這里先不展開(kāi)說(shuō)靠闭;children
表示當(dāng)前VNode
的子節(jié)點(diǎn)帐我,它是任意類型的,它接下來(lái)需要被規(guī)范為標(biāo)準(zhǔn)的VNode
數(shù)組愧膀;normalizationType
表示子節(jié)點(diǎn)規(guī)范的類型拦键,類型不同規(guī)范的方法也就不一樣,它主要是參考 render
函數(shù)是編譯生成的還是用戶手寫(xiě)的檩淋。
createElement
函數(shù)的流程略微有點(diǎn)多芬为,我們接下來(lái)主要分析2個(gè)重點(diǎn)的流程——children
的規(guī)范化以及VNode
的創(chuàng)建。
children的規(guī)范化
由于Virtual DOM實(shí)際上是一個(gè)樹(shù)狀結(jié)構(gòu)蟀悦,每一個(gè)VNode
可能會(huì)有若干個(gè)子節(jié)點(diǎn)媚朦,這些子節(jié)點(diǎn)應(yīng)該也是VNode
的類型。_createElement
接收的第 4個(gè)參數(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)用場(chǎng)景是render
函數(shù)是編譯生成的瑞侮。理論上編譯生成的children
都已經(jīng)是VNode
類型的,但這里有一個(gè)例外鼓拧,就是functional component
函數(shù)式組件返回的是一個(gè)數(shù)組而不是一個(gè)根節(jié)點(diǎn)半火,所以會(huì)通過(guò)Array.prototype.concat
方法把整個(gè)children
數(shù)組打平,讓它的深度只有一層季俩。
normalizeChildren
方法的調(diào)用場(chǎng)景有2種钮糖,一個(gè)場(chǎng)景是render
函數(shù)是用戶手寫(xiě)的,當(dāng)children
只有一個(gè)節(jié)點(diǎn)的時(shí)候酌住,Vue.js從接口層面允許用戶把children
寫(xiě)成基礎(chǔ)類型用來(lái)創(chuàng)建單個(gè)簡(jiǎn)單的文本節(jié)點(diǎn)店归,這種情況會(huì)調(diào)用createTextVNode
創(chuàng)建一個(gè)文本節(jié)點(diǎn)的VNode
;另一個(gè)場(chǎng)景是當(dāng)編譯slot
酪我、v-for
的時(shí)候會(huì)產(chǎn)生嵌套數(shù)組的情況消痛,會(huì)調(diào)用normalizeArrayChildren
方法,接下來(lái)看一下它的實(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ǔ)類型,則通過(guò)createTextVNode
方法轉(zhuǎn)換成VNode
類型未妹;否則就已經(jīng)是VNode
類型了阅羹,如果children
是一個(gè)列表并且列表還存在嵌套的情況勺疼,則根據(jù)nestedIndex
去更新它的key
教寂。這里需要注意一點(diǎn)捏鱼,在遍歷的過(guò)程中,對(duì)這3種情況都做了如下處理:如果存在兩個(gè)連續(xù)的text
節(jié)點(diǎn)酪耕,會(huì)把它們合并成一個(gè)text
節(jié)點(diǎn)导梆。
經(jīng)過(guò)對(duì)children
的規(guī)范化,children
變成了一個(gè)類型為VNode
的Array
迂烁。
VNode的創(chuàng)建
回到createElement
函數(shù)看尼,規(guī)范化children
后,接下來(lái)會(huì)去創(chuàng)建一個(gè)VNode
的實(shí)例:
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)
}
這里先對(duì)tag
做判斷盟步,如果是string
類型藏斩,則接著判斷如果是內(nèi)置的一些節(jié)點(diǎn),則直接創(chuàng)建一個(gè)普通VNode
却盘,如果是為已注冊(cè)的組件名狰域,則通過(guò)createComponent
創(chuàng)建一個(gè)組件類型的VNode
,否則創(chuàng)建一個(gè)未知的標(biāo)簽的VNode
黄橘。 如果是tag
一個(gè)Component
類型兆览,則直接調(diào)用createComponent
創(chuàng)建一個(gè)組件類型的VNode
節(jié)點(diǎn)。對(duì)于createComponent
創(chuàng)建組件類型的VNode
的過(guò)程塞关,本質(zhì)上它還是返回了一個(gè)VNode
抬探。
那么至此,我們大致了解了createElement
創(chuàng)建VNode
的過(guò)程帆赢,每個(gè)VNode
有children
小压,children
每個(gè)元素也是一個(gè)VNode
,這樣就形成了一個(gè)VNode Tree
椰于,它很好的描述了我們的 DOM Tree
怠益。
回到mountComponent
函數(shù)的過(guò)程,我們已經(jīng)知道vm._render
是如何創(chuàng)建了一個(gè)VNode
廉羔,接下來(lái)就是要把這個(gè)VNode
渲染成一個(gè)真實(shí)的DOM并渲染出來(lái)溉痢,這個(gè)過(guò)程是通過(guò)vm._update
完成的,接下來(lái)分析一下這個(gè)過(guò)程憋他。
update
Vue
的_update
是實(shí)例的一個(gè)私有方法孩饼,它被調(diào)用的時(shí)機(jī)有2個(gè),一個(gè)是首次渲染竹挡,一個(gè)是數(shù)據(jù)更新的時(shí)候镀娶。_update
方法的作用是把VNode
渲染成真實(shí)的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__
方法揪罕,這個(gè)方法實(shí)際上在不同的平臺(tái)梯码,比如web和weex上的定義是不一樣的宝泵,因此在web平臺(tái)中它的定義在src/platforms/web/runtime/index.js
中:
Vue.prototype.__patch__ = inBrowser ? patch : noop
可以看到,甚至在web平臺(tái)上轩娶,是否是服務(wù)端渲染也會(huì)對(duì)這個(gè)方法產(chǎn)生影響儿奶。因?yàn)樵诜?wù)端渲染中,沒(méi)有真實(shí)的瀏覽器DOM環(huán)境鳄抒,所以不需要把VNode
最終轉(zhuǎn)換成DOM闯捎,因此是一個(gè)空函數(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
方法的返回值,這里傳入了一個(gè)對(duì)象贤重,包含nodeOps
參數(shù)和modules
參數(shù)茬祷。其中,nodeOps
封裝了一系列DOM操作的方法并蝗,modules
定義了一些模塊的鉤子函數(shù)的實(shí)現(xiàn)祭犯,來(lái)看一下createPatchFunction
的實(shí)現(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)部定義了一系列的輔助方法借卧,最終返回了一個(gè)patch
方法盹憎,這個(gè)方法就賦值給了vm._update
函數(shù)里調(diào)用的vm.__patch__
。
在介紹patch
的方法實(shí)現(xiàn)之前铐刘,我們可以思考一下為何Vue.js源碼繞了這么一大圈陪每,把相關(guān)代碼分散到各個(gè)目錄。因?yàn)?code>patch是平臺(tái)相關(guān)的镰吵,在Web和Weex環(huán)境檩禾,它們把虛擬DOM映射到“平臺(tái)DOM”的方法是不同的,并且對(duì)“DOM”包括的屬性模塊創(chuàng)建和更新也不盡相同疤祭。因此每個(gè)平臺(tái)都有各自的nodeOps
和modules
盼产,它們的代碼需要托管在src/platforms
這個(gè)大目錄下。
而不同平臺(tái)的patch
的主要邏輯部分是相同的勺馆,所以這部分公共的部分托管在core
這個(gè)大目錄下戏售。差異化部分只需要通過(guò)參數(shù)來(lái)區(qū)別,這里用到了一個(gè)函數(shù)柯里化的技巧草穆,通過(guò)createPatchFunction
把差異化參數(shù)提前固化灌灾,這樣不用每次調(diào)用patch
的時(shí)候都傳遞nodeOps
和modules
了,這種編程技巧也非常值得學(xué)習(xí)悲柱。
在這里锋喜,nodeOps
表示對(duì)“平臺(tái) DOM”的一些操作方法,modules
表示平臺(tái)的一些模塊,它們會(huì)在整個(gè)patch
過(guò)程的不同階段執(zhí)行相應(yīng)的鉤子函數(shù)嘿般。
回到patch
方法本身段标,它接收4個(gè)參數(shù),oldVnode
表示舊的VNode
節(jié)點(diǎn)炉奴,它也可以不存在或者是一個(gè)DOM對(duì)象逼庞;vnode
表示執(zhí)行_render
后返回的VNode
的節(jié)點(diǎn);hydrating
表示是否是服務(wù)端渲染盆佣;removeOnly
是給transition-group
用的往堡。
先來(lái)回顧我們的例子:
var app = new Vue({
el: '#app',
render: function (createElement) {
return createElement('div', {
attrs: {
id: 'app'
},
}, this.message)
},
data: {
message: 'Hello Vue!'
}
})
然后我們?cè)?code>vm._update的方法里是這么調(diào)用patch
方法的:
// initial render
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
結(jié)合我們的例子,我們的場(chǎng)景是首次渲染共耍,所以在執(zhí)行patch
函數(shù)的時(shí)候,傳入的vm.$el
對(duì)應(yīng)的是例子中id
為app
的DOM對(duì)象吨瞎,這個(gè)也就是我們?cè)?code>index.html模板中寫(xiě)的<div id="app">
痹兜, vm.$el
的賦值是在之前mountComponent
函數(shù)做的,vnode
對(duì)應(yīng)的是調(diào)用render
函數(shù)的返回值颤诀,hydrating
在非服務(wù)端渲染情況下為false
字旭,removeOnly
為false
。
確定了這些入?yún)⒑笱陆校覀兓氐?code>patch函數(shù)的執(zhí)行過(guò)程遗淳,看幾個(gè)關(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
實(shí)際上是一個(gè)DOM container
心傀,所以isRealElement
為true
屈暗,接下來(lái)又通過(guò)emptyNodeAt
方法把oldVnode
轉(zhuǎn)換成VNode
對(duì)象,然后再調(diào)用createElm
方法脂男,這個(gè)方法在這里非常重要养叛,來(lái)看一下它的實(shí)現(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
的作用是通過(guò)虛擬節(jié)點(diǎn)創(chuàng)建真實(shí)的DOM并插入到它的父節(jié)點(diǎn)中。 我們來(lái)看一下它的一些關(guān)鍵邏輯宰翅,createComponent
方法目的是嘗試創(chuàng)建子組件弃甥,在當(dāng)前這個(gè)case
下它的返回值為false
;接下來(lái)判斷vnode
是否包含tag
汁讼,如果包含淆攻,先簡(jiǎn)單對(duì)tag
的合法性在非生產(chǎn)環(huán)境下做校驗(yàn),看是否是一個(gè)合法標(biāo)簽嘿架;然后再去調(diào)用平臺(tái)DOM的操作去創(chuàng)建一個(gè)占位符元素瓶珊。
vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag, vnode)
接下來(lái)調(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ǎn)單,實(shí)際上是遍歷子虛擬節(jié)點(diǎn)眶明,遞歸調(diào)用createElm
艰毒,這是一種常用的深度優(yōu)先的遍歷算法,這里要注意的一點(diǎn)是在遍歷過(guò)程中會(huì)把vnode.elm
作為父容器的DOM節(jié)點(diǎn)占位符傳入搜囱。
接著再調(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ǎn)中柑土,因?yàn)槭沁f歸調(diào)用,子元素會(huì)優(yōu)先調(diào)用insert
绊汹,所以整個(gè)vnode
樹(shù)節(jié)點(diǎn)的插入順序是先子后父稽屏。來(lái)看一下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
邏輯很簡(jiǎn)單狐榔,調(diào)用一些nodeOps
把子節(jié)點(diǎn)插入到父節(jié)點(diǎn)中,這些輔助方法定義在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)
}
其實(shí)就是調(diào)用原生DOM的API進(jìn)行DOM操作获雕。
在createElm
過(guò)程中薄腻,如果vnode
節(jié)點(diǎn)不包含tag
,則它有可能是一個(gè)注釋或者純文本節(jié)點(diǎn)届案,可以直接插入到父元素中庵楷。在我們這個(gè)例子中,最內(nèi)層就是一個(gè)文本 vnode
楣颠,它的text
值取的就是之前的this.message
的值Hello Vue!
尽纽。
再回到patch
方法,首次渲染我們調(diào)用了createElm
方法童漩,這里傳入的parentElm
是oldVnode.elm
的父元素弄贿,在我們的例子是id
為#app div
的父元素,也就是body
矫膨;實(shí)際上整個(gè)過(guò)程就是遞歸創(chuàng)建了一個(gè)完整的DOM樹(shù)并插入到body
上差凹。
最后,我們根據(jù)之前遞歸createElm
生成的vnode
插入順序隊(duì)列豆拨,執(zhí)行相關(guān)的insert
鉤子函數(shù)直奋。
總結(jié)
那么至此我們從主線上把模板和數(shù)據(jù)如何渲染成最終的DOM的過(guò)程分析完畢了,我們可以通過(guò)下圖更直觀地看到從初始化Vue
到最終渲染的整個(gè)過(guò)程施禾。