一栽烂、前言
本文介紹的內容包括:
- keep-alive用法:動態(tài)組件&vue-router
- keep-alive源碼解析
- keep-alive組件及其包裹組件的鉤子
- keep-alive組件及其包裹組件的渲染
二躏仇、keep-alive介紹與應用
2.1 keep-alive是什么
keep-alive是一個抽象組件:它自身不會渲染一個DOM元素,也不會出現(xiàn)在父組件鏈中腺办;使用keep-alive包裹動態(tài)組件時焰手,會緩存不活動的組件實例,而不是銷毀它們怀喉。
一個場景
用戶在某個列表頁面選擇篩選條件過濾出一份數(shù)據(jù)列表书妻,由列表頁面進入數(shù)據(jù)詳情頁面,再返回該列表頁面躬拢,我們希望:列表頁面可以保留用戶的篩選(或選中)狀態(tài)愿题。
keep-alive就是用來解決這種場景隅很。當然keep-alive不僅僅是能夠保存頁面/組件的狀態(tài)這么簡單,它還可以避免組件反復創(chuàng)建和渲染,有效提升系統(tǒng)性能日裙⊥疲總的來說圆兵,keep-alive用于保存組件的渲染狀態(tài)砾层。
keep-alive用法
- 在動態(tài)組件中的應用
<keep-alive :include="whiteList" :exclude="blackList" :max="amount">
<component :is="currentComponent"></component>
</keep-alive>
- 在vue-router中的應用
<keep-alive :include="whiteList" :exclude="blackList" :max="amount">
<router-view></router-view>
</keep-alive>
include定義緩存白名單史侣,keep-alive會緩存命中的組件;exclude定義緩存黑名單魏身,被命中的組件將不會被緩存惊橱;max定義緩存組件上限,超出上限使用LRU的策略置換緩存數(shù)據(jù)箭昵。
內存管理的一種頁面置換算法税朴,對于在內存中但又不用的數(shù)據(jù)塊(內存塊)叫做LRU,操作系統(tǒng)會根據(jù)哪些數(shù)據(jù)屬于LRU而將其移出內存而騰出空間來加載另外的數(shù)據(jù)家制。
三掉房、源碼剖析
keep-alive.js內部還定義了一些工具函數(shù),我們按住不動慰丛,先看它對外暴露的對象
// src/core/components/keep-alive.js
export default {
name: 'keep-alive',
abstract: true, // 判斷當前組件虛擬dom是否渲染成真實dom的關鍵
props: {
include: patternTypes, // 緩存白名單
exclude: patternTypes, // 緩存黑名單
max: [String, Number] // 緩存的組件
},
created() {
this.cache = Object.create(null) // 緩存虛擬dom
this.keys = [] // 緩存的虛擬dom的鍵集合
},
destroyed() {
for (const key in this.cache) {
// 刪除所有的緩存
pruneCacheEntry(this.cache, key, this.keys)
}
},
mounted() {
// 實時監(jiān)聽黑白名單的變動
this.$watch('include', val => {
pruneCache(this, name => matched(val, name))
})
this.$watch('exclude', val => {
pruneCache(this, name => !matches(val, name))
})
},
render() {
// 先省略...
}
}
可以看出卓囚,與我們定義組件的過程一樣,先是設置組件名為keep-alive诅病,其次定義了一個abstract屬性哪亿,值為true。這個屬性在vue的官方教程并未提及贤笆,卻至關重要蝇棉,后面的渲染過程會用到。props屬性定義了keep-alive組件支持的全部參數(shù)芥永。
keep-alive在它生命周期內定義了三個鉤子函數(shù):
- created
初始化兩個對象分別緩存VNode(虛擬DOM)和VNode對應的鍵集合 - destroyed
刪除this.cache中緩存的VNode實例篡殷。我們留意到,這不是簡單地將this.cache置為null埋涧,而是遍歷調用pruneCacheEntry函數(shù)刪除板辽。
// src/core/components/keep-alive.js
function pruneCacheEntry (
cache: VNodeCache,
key: string,
keys: Array<string>,
current?: VNode
) {
const cached = cache[key]
if (cached && (!current || cached.tag !== current.tag)) {
cached.componentInstance.$destroyed() // 執(zhí)行組件的destroy鉤子函數(shù)
}
cache[key] = null
remove(keys, key)
}
刪除緩存的VNode還要對應組件實例的destory鉤子函數(shù)
- mounted
在mounted這個鉤子中對include和exclude參數(shù)進行監(jiān)聽,然后實時地更新(刪除)this.cache對象數(shù)據(jù)棘催。pruneCache函數(shù)的核心也是去調用pruneCacheEntry
function pruneCache (keepAliveInstance: any, filter: Function) {
const { cache, keys, _vnode } = keepAliveInstance
for (const key in cache) {
const cachedNode: ?VNode = cache[key]
if (cachedNode) {
const name: ?string = getComponentName(cachedNode.componentOptions)
if (name && !filter(name)) {
pruneCacheEntry(cache, key, keys, _vnode)
}
}
}
}
- render
render () {
const slot = this.$slots.defalut
const vnode: VNode = getFirstComponentChild(slot) // 找到第一個子組件對象
const componentOptions : ?VNodeComponentOptions = vnode && vnode.componentOptions
if (componentOptions) { // 存在組件參數(shù)
// check pattern
const name: ?string = getComponentName(componentOptions) // 組件名
const { include, exclude } = this
if (// 條件匹配
// not included
(include && (!name || !matches(include, name)))||
// excluded
(exclude && name && matches(exclude, name))
) {
return vnode
}
const { cache, keys } = this
// 定義組件的緩存key
const key: ?string = vnode.key === null ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '') : vnode.key
if (cache[key]) { // 已經(jīng)緩存過該組件
vnode.componentInstance = cache[key].componentInstance
remove(keys, key)
keys.push(key) // 調整key排序
} else {
cache[key] = vnode //緩存組件對象
keys.push(key)
if (this.max && keys.length > parseInt(this.max)) {
//超過緩存數(shù)限制劲弦,將第一個刪除
pruneCacheEntry(cahce, keys[0], keys, this._vnode)
}
}
vnode.data.keepAlive = true //渲染和執(zhí)行被包裹組件的鉤子函數(shù)需要用到
}
return vnode || (slot && slot[0])
}
- 第一步:獲取keep-alive包裹著的第一個子組件對象及其組件名;
- 第二步:根據(jù)設定的黑白名單(如果有)進行條件匹配醇坝,決定是否緩存邑跪。不匹配,直接返回組件實例(VNode)呼猪,否則執(zhí)行第三步画畅;
- 第三步:根據(jù)組件ID和tag生成緩存Key,并在緩存對象中查找是否已緩存過該組件實例宋距。如果存在轴踱,直接取出緩存值并更新該key在this.keys中的位置(更新key的位置是實現(xiàn)LRU置換策略的關鍵),否則執(zhí)行第四步乡革;
- 第四步:在this.cache對象中存儲該組件實例并保存key值寇僧,之后檢查緩存的實例數(shù)量是否超過max設置值摊腋,超過則根據(jù)LRU置換策略刪除最近最久未使用的實例(即是下標為0的那個key);
- 第五步:最后并且很重要沸版,將該組件實例的keepAlive屬性值設置為true嘁傀。
四、重頭戲:渲染
4.1 Vue的渲染過程
借助一張圖看下Vue渲染的整個過程:
Vue的渲染是從圖中render階段開始的视粮,但keep-alive的渲染是在patch階段细办,這是構建組件樹(虛擬DOM樹),并將VNode轉換成真正DOM節(jié)點的過程蕾殴。
簡單描述從render到patch的過程
我們從最簡單的new Vue開始:
import App from './App.vue'
new Vue({
render: h => h(App)
}).$mount('#app')
Vue在渲染的時候先調用原型上的_render函數(shù)將組件對象轉化成一個VNode實例笑撞;而_render是通過調用createElement和createEmptyVNode兩個函數(shù)進行轉化;
createElement的轉化過程會根據(jù)不同的情形選擇new VNode或者調用createComponent函數(shù)做VNode實例化钓觉;
-
完成VNode實例化后茴肥,這時候Vue調用原型上的_update函數(shù)把VNode渲染成真實DOM,這個過程又是通過調用patch函數(shù)完成的(這就是patch階段了)
用一張圖表達:image
4.2 keep-alive組件的渲染
我們用過keep-alive都知道荡灾,它不會生成真正的DOM節(jié)點瓤狐,這是怎么做到的?
// src/core/instance/lifecycle.js
export function initLifecycle (vm: Component) {
const options= vm.$options
// 找到第一個非abstract父組件實例
let parent = options.parent
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent
}
parent.$children.push(vm)
}
vm.$parent = parent
// ...
}
Vue在初始化生命周期的時候批幌,為組件實例建立父子關系會根據(jù)abstract屬性決定是否忽略某個組件础锐。在keep-alive中,設置了abstract:true荧缘,那Vue就會跳過該組件實例皆警。
最后構建的組件樹中就不會包含keep-alive組件,那么由組件樹渲染成的DOM樹自然也不會有keep-alive相關的節(jié)點了截粗。
keep-alive包裹的組件是如何使用緩存的信姓?
在patch階段,會執(zhí)行createComponent函數(shù):
// src/core/vdom/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)
}
if (isDef(vnode.componentInstance)) {
initComponent(vnode, insertedVnodeQueue)
insert(parentElem, vnode.elem, refElem) // 將緩存的DOM(vnode.elem) 插入父元素中
if (isTrue(isReactivated)) {
reactivateComponent(vnode, insertedVnodeQueue, parentEle, refElm)
}
return true
}
}
}
- 在首次加載被包裹組建時绸罗,由keep-alive.js中的render函數(shù)可知财破,vnode.componentInstance的值是undfined,keepAlive的值是true从诲,因為keep-alive組件作為父組件左痢,它的render函數(shù)會先于被包裹組件執(zhí)行;那么只執(zhí)行到i(vnode,false)系洛,后面的邏輯不執(zhí)行俊性;
- 再次訪問被包裹組件時,vnode.componentInstance的值就是已經(jīng)緩存的組件實例描扯,那么會執(zhí)行insert(parentElm, vnode.elm, refElm)邏輯定页,這樣就直接把上一次的DOM插入到父元素中。
五绽诚、不可忽視:鉤子函數(shù)
5.1 只執(zhí)行一次的鉤子
一般的組件典徊,每一次加載都會有完整的生命周期杭煎,即生命周期里面對于的鉤子函數(shù)都會被觸發(fā),為什么被keep-alive包裹的組件卻不是呢卒落?
被緩存的組件實例會為其設置keepAlive= true羡铲,而在初始化組件鉤子函數(shù)中:
// src/core/vdom/create-component.js
const componentVNodeHooks = {
init (vnode: VNodeWithData, hydrating: boolean): ?boolean{
if (
vnode.componentInstance &&
!vnode.componentInstance._isDestroyed &&
vnode.data.keepAlive
) {
// keep-alive components, treat as a patch
const mountedNode:any = vnode
componentVNodeHooks.prepatch(mountedNode, mountedNode)
} else {
const child = vnode.componentInstance = createComponentInstanceForVnode (vnode, activeInstance)
}
}
}
可以看出,當vnode.componentInstance和keepAlive同時為true時儡毕,不再進入$mount過程也切,那mounted之前的所有鉤子函數(shù)(beforeCreate、created腰湾、mounted)都不再執(zhí)行雷恃。
5.2 可重復的activated
在patch的階段,最后會執(zhí)行invokeInsertHook函數(shù)费坊,而這個函數(shù)就是去調用組件實例(VNode)自身的insert鉤子:
// src/core/vdom/patch.js
function invokeInsertHook (vnode, queue, initial) {
if (isTrue(initial) && isDef(vnode.parent)) {
vnode.parent.data,pendingInsert = queue
} else {
for(let i =0; i<queue.length; ++i) {
queue[i].data.hook.insert(queue[i]) // 調用VNode自身的insert鉤子函數(shù)
}
}
}
再看insert鉤子:
const componentVNodeHooks = {
// init()
insert (vnode: MountedComponentVNode) {
const { context, componentInstance } = vnode
if (!componentInstance._isMounted) {
componentInstance._isMounted = true
callHook(componentInstance, 'mounted')
}
if (vnode.data.keepAlive) {
if (context._isMounted) {
queueActivatedComponent(componentInstance)
} else {
activateChildComponent(componentInstance, true/* direct */)
}
}
// ...
}
}
在這個鉤子里面倒槐,調用了activateChildComponent函數(shù)遞歸地去執(zhí)行所有子組件的activated鉤子函數(shù):
// src/core/instance/lifecycle.js
export function activateChildComponent (vm: Component, direct?: boolean) {
if (direct) {
vm._directInactive = false
if (isInInactiveTree(vm)) {
return
}
} else if (vm._directInactive) {
return
}
if (vm._inactive || vm._inactive === null) {
vm._inactive = false
for (let i = 0; i < vm.$children.length; i++) {
activateChildComponent(vm.$children[i])
}
callHook(vm, 'activated')
}
}
相反地,deactivated鉤子函數(shù)也是一樣的原理附井,在組件實例(VNode)的destroy鉤子函數(shù)中調用deactivateChildComponent函數(shù)讨越。
參考
作者:amCow
鏈接:http://www.reibang.com/p/9523bb439950