當通過 crateComponent 創建了組件 VNode,接下來會走到 vm._update,執行 vm._update,執行 vm.path 去把 VNode 轉換成真正的 DOM 節點。但這些只是針對于一個普通的 VNode 節點,現在來看一下組件的 VNode 會有哪些不一樣的地方。
-
patch 過程會調用 createElm 創建元素節點,看一下 createElm 的實現,定義在 src/core/vdom/patch.js 中:
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 } ... }
createComponent
-
這里有個關鍵的邏輯,這里會判斷 createComponent(vnode, insertedVnodeQueue, parentElm, refElm) 的返回值,如果為 true 則直接結束,接下來就先看一下 createComponent 方法:
function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { let i = vnode.data if (isDef(i)) { const isReactivated = isDef(vnode.componentInstance) && i.keepAlive if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */, parentElm, refElm) } // after calling the init hook, if the vnode is a child component // it should've created a child instance and mounted it. the child // component also has set the placeholder vnode's elm. // in that case we can just return the element and be done. if (isDef(vnode.componentInstance)) { initComponent(vnode, insertedVnodeQueue) if (isTrue(isReactivated)) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm) } return true } } }
-
createComponent 函數中,首先對 vnode.data 做一些判斷操作:
let i = vnode.data if (isDef(i)) { // ... if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */, parentElm, refElm) } }
-
如果 VNode 是一個組件 VNode,那么這個條件會被滿足,并且得到 i 就是 init 鉤子函數,之前提到過,在創建組件 VNode 的時候合并鉤子函數就是包含 init 鉤子函數,它定義在 src/core/vdom/create-component.js
init ( vnode: VNodeWithData, hydrating: boolean, parentElm: ?Node, refElm: ?Node ): ?boolean { if ( vnode.componentInstance && !vnode.componentInstance._isDestroyed && vnode.data.keepAlive ) { // kept-alive components, treat as a patch const mountedNode: any = vnode // work around flow componentVNodeHooks.prepatch(mountedNode, mountedNode) } else { const child = vnode.componentInstance = createComponentInstanceForVnode( vnode, activeInstance, parentElm, refElm ) child.$mount(hydrating ? vnode.elm : undefined, hydrating) }
-
init 鉤子函數執行也比較簡單,首先不考慮 keepAlive 的情況,它是通過 createComponentInstanceForVnode 創建一個 Vue 的實例,然后調用 $mount 方法掛載子組件,看一下 createComponentInstanceForVnode 的實現:
export function createComponentInstanceForVnode ( vnode: any, // we know it's MountedComponentVNode but flow doesn't parent: any, // activeInstance in lifecycle state parentElm?: ?Node, refElm?: ?Node ): Component { const options: InternalComponentOptions = { _isComponent: true, parent, _parentVnode: vnode, _parentElm: parentElm || null, _refElm: refElm || null } // check inline-template render functions const inlineTemplate = vnode.data.inlineTemplate if (isDef(inlineTemplate)) { options.render = inlineTemplate.render options.staticRenderFns = inlineTemplate.staticRenderFns } return new vnode.componentOptions.Ctor(options) }
createComponentInstanceForVnode 函數構造的一個內容組件的參數,然后執行 new vnode.componentOptions.Ctor(options)。其中這里的 vnode.componentOptions.Ctor 對應的就是子組件的構造函數,前面的小章節中分析了它實際上就是繼承于 Vue 的一個構造器 Sub, 相當于 new Sub(options) 這里的參數需要注意一下: _ isComponent: true 表示它是一個組件,parent 表示當前激活的組件實例。
-
所以子組件的實例化實際上就是在這個時機執行的,并且它會執行實例的 _init 方法,代碼在 src/core/instance/init.js 中
Vue.prototype._init = function (options?: Object) { const vm: Component = this // a uid vm._uid = uid++ let startTag, endTag /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { startTag = `vue-perf-start:${vm._uid}` endTag = `vue-perf-end:${vm._uid}` mark(startTag) } // a flag to avoid this being observed vm._isVue = true // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options) } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ) } // ... if (vm.$options.el) { vm.$mount(vm.$options.el) } }
-
首先是合并 options 的過程變化,_isComponent 為 true,然后會走到 initInternalComponent 過程,先看一下這個函數:
export function initInternalComponent (vm: Component, options: InternalComponentOptions) { const opts = vm.$options = Object.create(vm.constructor.options) // doing this because it's faster than dynamic enumeration. const parentVnode = options._parentVnode opts.parent = options.parent opts._parentVnode = parentVnode opts._parentElm = options._parentElm opts._refElm = options._refElm const vnodeComponentOptions = parentVnode.componentOptions opts.propsData = vnodeComponentOptions.propsData opts._parentListeners = vnodeComponentOptions.listeners opts._renderChildren = vnodeComponentOptions.children opts._componentTag = vnodeComponentOptions.tag if (options.render) { opts.render = options.render opts.staticRenderFns = options.staticRenderFns } }
-
在這個過程中,要記住幾點: opts.parent = options.parent、opts._parentVnode = parentVnode, opts._parentElm = options._parentElm, opts._refElm = options._refElm 它們就是之前通過 createComponentInstanceForVnode 函數傳入的幾個參數合并到了內容選項 $optons 中了。
在看一下 _init 函數最后的執行的代碼:if (vm.$options.el) { vm.$mount(vm.$options.el) }
-
由于組件初始化的時候是不傳 el 的,因此組件是自己接管了 、$mount 的過程,這個過程的主要流程在 $mount 章節中已經介紹過了,現在看組件 init 的過程,componentVnodeHooks (代碼在: src/core/vdom/create-component.js) 的 init 鉤子函數,在完成實例化的 init 后,接著會執行 child.$mount(hydrating ? vnode.elm : undefined, hydrating)。這里 hydrating 為 true 一般是服務器渲染的情況,現在只考慮客戶端渲染,所以這里 $mount 相當于執行了 child.$mount(undefined, false), 它最終會調用 mountComponent 方法,從而執行了 vm._render() 方法:
Vue.prototype._render = function (): VNode { const vm: Component = this const { render, _parentVnode } = vm.$options ... // set parent vnode. this allows render functions to have access // to the data on the placeholder node. vm.$vnode = _parentVnode // render self let vnode try { vnode = render.call(vm._renderProxy, vm.$createElement) } catch (e) { handleError(e, vm, `render`) // return error render result, // or previous vnode to prevent render error causing blank component /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { if (vm.$options.renderError) { try { vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e) } catch (e) { handleError(e, vm, `renderError`) vnode = vm._vnode } } else { vnode = vm._vnode } } else { vnode = vm._vnode } } ... // set parent vnode.parent = _parentVnode return vnode }
上面這里只保留了一些部分關鍵的代碼, _parentVnode 就是當前組件的父 VNode,而 render 函數生成的 vnode 當前組件渲染 vnode,vnode 的 parent 指向了 _parentVnode,其實也就是 vm.$vnode,他們是一種父子的關系。
-
在執行完 vm._render 生成 VNode 之后,接下來會執行 vm._update 去渲染 VNode,看一下 _update 的定義,在 src/core/instance/lifecycle.js 中:
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) { const vm: Component = this if (vm._isMounted) { callHook(vm, 'beforeUpdate') } 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 */, vm.$options._parentElm, vm.$options._refElm ) // no need for the ref nodes after initial patch // this prevents keeping a detached DOM tree in memory (#5851) vm.$options._parentElm = vm.$options._refElm = null } 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 過程中有幾個關鍵的地方(代碼),首先是 vm._vnode = vnode 的邏輯,這個 vnode 是通過 vm._render() 返回的組件渲染 VNode,vm._vnode 和 vm.$vnode 的關系就是父子關系,用代碼就是 vm.vnode.parent === vm.$vnode。
-
這段代碼也是很有意思:
export let activeInstance: any = null 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 */, vm.$options._parentElm, vm.$options._refElm ) // no need for the ref nodes after initial patch // this prevents keeping a detached DOM tree in memory (#5851) vm.$options._parentElm = vm.$options._refElm = null } else { // updates vm.$el = vm.__patch__(prevVnode, vnode) } activeInstance = prevActiveInstance
這個 activeInstance 作用就是保持當前上下文的 Vue 實例,它是在 lifecycle 模塊的全局變量,定義 export let activeInstance: any = null,并且在之前調用 createComponentInstanceForVnode 方法的時候從 lifecycle 模塊獲取,并且作為參數傳入的。
因為 JavaScript 是一個單線程,Vue 整個初始化時一個深度便遍歷的過程,咋實例化子組件的過程中,它需要知道當前上下文的 Vue 實例是什么,并把它作為子組件的父 Vue 實例。之前有提到過對組組件的實例過程會先調用 initInternalComponent(vm, options) 合并 options,把 parent 存儲到 vm.$options 中,在$mount 之前會調用 initLifecycle(vm) 方法:
export function initLifecycle (vm: Component) {
const options = vm.$options
// locate first non-abstract parent
let parent = options.parent
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent
}
parent.$children.push(vm)
}
vm.$parent = parent
...
}
上面可以看到 vm.$parent 就是用來保留當前 vm 的父實例,并且通過 parent.$children.push(vm) 來把當前的 vm 存儲到父實例的 $children 中。
在 vm._update 的過程中,把當前的 vm 賦值給 activeInstance,同時通過 const prevActiveInstance = activeInstance 用 prevActiveInstance 保留上一次的 activeInstance。實際上,prevActiveInstance 和當前的 vm 是一個父子關系,當一個 vm 實例完成它的所有子樹的 patch 或者 update 過程后,activeInstance 會回到它的父實例,這個就美的保證了 crateComponentInstanceForVnode 整個深度遍歷過程中,在實例化子組件的時候能傳入當前子組件的父 Vue 實例,并在 _init 的過程中,通過 vm.$parent 把父子關系保留。
回到 _update,最后就是調用 patch 渲染 VNode 。
vm.$el = vm.__patch__(
vm.$el, vnode, hydrating, false /* removeOnly */,
vm.$options._parentElm,
vm.$options._refElm
)
function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) {
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, parentElm, refElm)
} else {
...
}
...
}
- 這里就又回到了本文開始的地方,之前分析過負責渲染 DOM 的函數是 createElm,注意這里只傳了兩個參數,所以對應的 parentElm 是 undefined。再看一下它的定義:
function createElm (
vnode,
insertedVnodeQueue,
parentElm,
refElm,
nested,
ownerArray,
index
) {
...
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)
}
}
這里我們傳入的 vnode 是組件渲染的 vnode,也就是之前說的 vm._vnode,如果組件的根節點是普通元素,那么 vm._vnode 也是普通的 vnode,這里 createComponent(vnode, insertedVnodeQueue, parentElm, refElm) 的返回值就是 false,接下來的過程就和 我之前寫過的 createComponent(Vue 創建組件) 是一樣的。先創建一個父節點占位符,然后在遍歷所有的子 VNode 遞推調用 crateElm,在遍歷過程中,如果遇到子 VNode 是一個組件的 VNode,則重復本文開始的過程,通過一個遞歸的方式就可以完成整個組件數的構建。
-
由于這個時候傳入的 parentElm 是空,所以對組件的插入,在 createComponent 有這個一段邏輯在 patch.js 文件中:
function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { let i = vnode.data if (isDef(i)) { const isReactivated = isDef(vnode.componentInstance) && i.keepAlive if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */, parentElm, refElm) } // after calling the init hook, if the vnode is a child component // it should've created a child instance and mounted it. the child // component also has set the placeholder vnode's elm. // in that case we can just return the element and be done. if (isDef(vnode.componentInstance)) { initComponent(vnode, insertedVnodeQueue) if (isTrue(isReactivated)) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm) } return true } } }
在完成組件整個 parch 過程后,最后執行 nsert(parentElm, vnode.elm, refElm) 完成組件的 DOM 插入,如果組件 patch 過程中又創建了子組件,那么 DOM 的插入順序是
先子后父
。