一哑梳、前言
本文介紹的內(nèi)容包括:
keep-alive用法:動(dòng)態(tài)組件&vue-router
keep-alive源碼解析
keep-alive組件及其包裹組件的鉤子
keep-alive組件及其包裹組件的渲染
二、keep-alive介紹與應(yīng)用
2.1 keep-alive是什么
keep-alive是一個(gè)抽象組件:它自身不會(huì)渲染一個(gè)DOM元素绘盟,也不會(huì)出現(xiàn)在父組件鏈中鸠真;使用keep-alive包裹動(dòng)態(tài)組件時(shí),會(huì)緩存不活動(dòng)的組件實(shí)例龄毡,而不是銷毀它們吠卷。
一個(gè)場(chǎng)景
用戶在某個(gè)列表頁(yè)面選擇篩選條件過(guò)濾出一份數(shù)據(jù)列表,由列表頁(yè)面進(jìn)入數(shù)據(jù)詳情頁(yè)面沦零,再返回該列表頁(yè)面祭隔,我們希望:列表頁(yè)面可以保留用戶的篩選(或選中)狀態(tài)。
keep-alive就是用來(lái)解決這種場(chǎng)景路操。當(dāng)然keep-alive不僅僅是能夠保存頁(yè)面/組件的狀態(tài)這么簡(jiǎn)單疾渴,它還可以避免組件反復(fù)創(chuàng)建和渲染,有效提升系統(tǒng)性能屯仗「惆樱總的來(lái)說(shuō),keep-alive用于保存組件的渲染狀態(tài)魁袜。
keep-alive用法
在動(dòng)態(tài)組件中的應(yīng)用
<keep-alive:include="whiteList":exclude="blackList":max="amount"><component:is="currentComponent"></component></keep-alive>
在vue-router中的應(yīng)用
<keep-alive:include="whiteList":exclude="blackList":max="amount"><router-view></router-view></keep-alive>
include定義緩存白名單桩撮,keep-alive會(huì)緩存命中的組件;exclude定義緩存黑名單峰弹,被命中的組件將不會(huì)被緩存店量;max定義緩存組件上限,超出上限使用LRU的策略置換緩存數(shù)據(jù)鞠呈。
內(nèi)存管理的一種頁(yè)面置換算法融师,對(duì)于在內(nèi)存中但又不用的數(shù)據(jù)塊(內(nèi)存塊)叫做LRU,操作系統(tǒng)會(huì)根據(jù)哪些數(shù)據(jù)屬于LRU而將其移出內(nèi)存而騰出空間來(lái)加載另外的數(shù)據(jù)粟按。
三诬滩、源碼剖析
keep-alive.js內(nèi)部還定義了一些工具函數(shù)霹粥,我們按住不動(dòng)灭将,先看它對(duì)外暴露的對(duì)象
// src/core/components/keep-alive.jsexport default{name:'keep-alive',abstract:true,// 判斷當(dāng)前組件虛擬dom是否渲染成真實(shí)dom的關(guān)鍵props:{include:patternTypes,// 緩存白名單exclude:patternTypes,// 緩存黑名單max:[String,Number]// 緩存的組件},created(){this.cache=Object.create(null)// 緩存虛擬domthis.keys=[]// 緩存的虛擬dom的鍵集合},destroyed(){for(constkeyinthis.cache){// 刪除所有的緩存pruneCacheEntry(this.cache,key,this.keys)}},mounted(){// 實(shí)時(shí)監(jiān)聽(tīng)黑白名單的變動(dòng)this.$watch('include',val=>{pruneCache(this,name=>matched(val,name))})this.$watch('exclude',val=>{pruneCache(this,name=>!matches(val,name))})},render(){// 先省略...}}
可以看出疼鸟,與我們定義組件的過(guò)程一樣,先是設(shè)置組件名為keep-alive庙曙,其次定義了一個(gè)abstract屬性空镜,值為true。這個(gè)屬性在vue的官方教程并未提及捌朴,卻至關(guān)重要吴攒,后面的渲染過(guò)程會(huì)用到。props屬性定義了keep-alive組件支持的全部參數(shù)砂蔽。
keep-alive在它生命周期內(nèi)定義了三個(gè)鉤子函數(shù):
created
初始化兩個(gè)對(duì)象分別緩存VNode(虛擬DOM)和VNode對(duì)應(yīng)的鍵集合
destroyed
刪除this.cache中緩存的VNode實(shí)例洼怔。我們留意到,這不是簡(jiǎn)單地將this.cache置為null左驾,而是遍歷調(diào)用pruneCacheEntry函數(shù)刪除镣隶。
// src/core/components/keep-alive.jsfunctionpruneCacheEntry(cache:VNodeCache,key:string,keys:Array<string>,
? current?: VNode
) {constcached=cache[key]if(cached&&(!current||cached.tag!==current.tag)){cached.componentInstance.$destroyed()// 執(zhí)行組件的destroy鉤子函數(shù)}cache[key]=nullremove(keys,key)}
刪除緩存的VNode還要對(duì)應(yīng)組件實(shí)例的destory鉤子函數(shù)
mounted
在mounted這個(gè)鉤子中對(duì)include和exclude參數(shù)進(jìn)行監(jiān)聽(tīng),然后實(shí)時(shí)地更新(刪除)this.cache對(duì)象數(shù)據(jù)诡右。pruneCache函數(shù)的核心也是去調(diào)用pruneCacheEntry
functionpruneCache(keepAliveInstance:any,filter:Function){const{cache,keys,_vnode}=keepAliveInstancefor(constkeyincache){constcachedNode:?VNode=cache[key]if(cachedNode){constname:?string=getComponentName(cachedNode.componentOptions)if(name&&!filter(name)){pruneCacheEntry(cache,key,keys,_vnode)}}}}
render
render(){constslot=this.$slots.defalutconstvnode:VNode=getFirstComponentChild(slot)// 找到第一個(gè)子組件對(duì)象constcomponentOptions:?VNodeComponentOptions=vnode&&vnode.componentOptionsif(componentOptions){// 存在組件參數(shù)// check patternconstname:?string=getComponentName(componentOptions)// 組件名const{include,exclude}=thisif(// 條件匹配// not included(include&&(!name||!matches(include,name)))||// excluded(exclude&&name&&matches(exclude,name))){returnvnode}const{cache,keys}=this// 定義組件的緩存keyconstkey:?string=vnode.key===null?componentOptions.Ctor.cid+(componentOptions.tag?`::${componentOptions.tag}`:''):vnode.keyif(cache[key]){// 已經(jīng)緩存過(guò)該組件vnode.componentInstance=cache[key].componentInstanceremove(keys,key)keys.push(key)// 調(diào)整key排序}else{cache[key]=vnode//緩存組件對(duì)象keys.push(key)if(this.max&&keys.length>parseInt(this.max)){//超過(guò)緩存數(shù)限制安岂,將第一個(gè)刪除pruneCacheEntry(cahce,keys[0],keys,this._vnode)}}vnode.data.keepAlive=true//渲染和執(zhí)行被包裹組件的鉤子函數(shù)需要用到}returnvnode||(slot&&slot[0])}
第一步:獲取keep-alive包裹著的第一個(gè)子組件對(duì)象及其組件名;
第二步:根據(jù)設(shè)定的黑白名單(如果有)進(jìn)行條件匹配帆吻,決定是否緩存域那。不匹配,直接返回組件實(shí)例(VNode)猜煮,否則執(zhí)行第三步次员;
第三步:根據(jù)組件ID和tag生成緩存Key,并在緩存對(duì)象中查找是否已緩存過(guò)該組件實(shí)例王带。如果存在翠肘,直接取出緩存值并更新該key在this.keys中的位置(更新key的位置是實(shí)現(xiàn)LRU置換策略的關(guān)鍵),否則執(zhí)行第四步辫秧;
第四步:在this.cache對(duì)象中存儲(chǔ)該組件實(shí)例并保存key值束倍,之后檢查緩存的實(shí)例數(shù)量是否超過(guò)max設(shè)置值,超過(guò)則根據(jù)LRU置換策略刪除最近最久未使用的實(shí)例(即是下標(biāo)為0的那個(gè)key);
第五步:最后并且很重要盟戏,將該組件實(shí)例的keepAlive屬性值設(shè)置為true绪妹。
四、重頭戲:渲染
4.1 Vue的渲染過(guò)程
借助一張圖看下Vue渲染的整個(gè)過(guò)程:
vue渲染過(guò)程.png
Vue的渲染是從圖中render階段開(kāi)始的柿究,但keep-alive的渲染是在patch階段邮旷,這是構(gòu)建組件樹(shù)(虛擬DOM樹(shù))龟再,并將VNode轉(zhuǎn)換成真正DOM節(jié)點(diǎn)的過(guò)程厂镇。
簡(jiǎn)單描述從render到patch的過(guò)程
我們從最簡(jiǎn)單的new Vue開(kāi)始:
importAppfrom'./App.vue'newVue({render:h=>h(App)}).$mount('#app')
Vue在渲染的時(shí)候先調(diào)用原型上的_render函數(shù)將組件對(duì)象轉(zhuǎn)化成一個(gè)VNode實(shí)例;而_render是通過(guò)調(diào)用createElement和createEmptyVNode兩個(gè)函數(shù)進(jìn)行轉(zhuǎn)化;
createElement的轉(zhuǎn)化過(guò)程會(huì)根據(jù)不同的情形選擇new VNode或者調(diào)用createComponent函數(shù)做VNode實(shí)例化樊销;
完成VNode實(shí)例化后,這時(shí)候Vue調(diào)用原型上的_update函數(shù)把VNode渲染成真實(shí)DOM踊挠,這個(gè)過(guò)程又是通過(guò)調(diào)用patch函數(shù)完成的(這就是patch階段了)
用一張圖表達(dá):
渲染過(guò)程.png
4.2 keep-alive組件的渲染
我們用過(guò)keep-alive都知道弄唧,它不會(huì)生成真正的DOM節(jié)點(diǎn),這是怎么做到的险毁?
// src/core/instance/lifecycle.jsexportfunctioninitLifecycle(vm:Component){constoptions=vm.$options// 找到第一個(gè)非abstract父組件實(shí)例letparent=options.parentif(parent&&!options.abstract){while(parent.$options.abstract&&parent.$parent){parent=parent.$parent}parent.$children.push(vm)}vm.$parent=parent// ...}
Vue在初始化生命周期的時(shí)候制圈,為組件實(shí)例建立父子關(guān)系會(huì)根據(jù)abstract屬性決定是否忽略某個(gè)組件。在keep-alive中畔况,設(shè)置了abstract:true鲸鹦,那Vue就會(huì)跳過(guò)該組件實(shí)例。
最后構(gòu)建的組件樹(shù)中就不會(huì)包含keep-alive組件跷跪,那么由組件樹(shù)渲染成的DOM樹(shù)自然也不會(huì)有keep-alive相關(guān)的節(jié)點(diǎn)了馋嗜。
keep-alive包裹的組件是如何使用緩存的?
在patch階段吵瞻,會(huì)執(zhí)行createComponent函數(shù):
// src/core/vdom/patch.jsfunction createComponent(vnode,insertedVnodeQueue,parentElm,refElm){leti=vnode.dataif(isDef(i)){constisReactivated=isDef(vnode.componentInstance)&&i.keepAliveif(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)}returntrue}}}
在首次加載被包裹組建時(shí)葛菇,由keep-alive.js中的render函數(shù)可知,vnode.componentInstance的值是undfined听皿,keepAlive的值是true熟呛,因?yàn)閗eep-alive組件作為父組件,它的render函數(shù)會(huì)先于被包裹組件執(zhí)行尉姨;那么只執(zhí)行到i(vnode,false)庵朝,后面的邏輯不執(zhí)行;
再次訪問(wèn)被包裹組件時(shí)又厉,vnode.componentInstance的值就是已經(jīng)緩存的組件實(shí)例九府,那么會(huì)執(zhí)行insert(parentElm, vnode.elm, refElm)邏輯,這樣就直接把上一次的DOM插入到父元素中覆致。
五侄旬、不可忽視:鉤子函數(shù)
5.1 只執(zhí)行一次的鉤子
一般的組件,每一次加載都會(huì)有完整的生命周期煌妈,即生命周期里面對(duì)于的鉤子函數(shù)都會(huì)被觸發(fā)儡羔,為什么被keep-alive包裹的組件卻不是呢?
被緩存的組件實(shí)例會(huì)為其設(shè)置keepAlive= true璧诵,而在初始化組件鉤子函數(shù)中:
// src/core/vdom/create-component.jsconstcomponentVNodeHooks={init(vnode:VNodeWithData,hydrating:boolean):?boolean{if(vnode.componentInstance&&!vnode.componentInstance._isDestroyed&&vnode.data.keepAlive){// keep-alive components, treat as a patchconstmountedNode:any=vnode? ? ? ? ? componentVNodeHooks.prepatch(mountedNode,mountedNode)}else{constchild=vnode.componentInstance=createComponentInstanceForVnode(vnode,activeInstance)}}}
可以看出汰蜘,當(dāng)vnode.componentInstance和keepAlive同時(shí)為true時(shí),不再進(jìn)入$mount過(guò)程之宿,那mounted之前的所有鉤子函數(shù)(beforeCreate族操、created、mounted)都不再執(zhí)行比被。
5.2 可重復(fù)的activated
在patch的階段色难,最后會(huì)執(zhí)行invokeInsertHook函數(shù)泼舱,而這個(gè)函數(shù)就是去調(diào)用組件實(shí)例(VNode)自身的insert鉤子:
// src/core/vdom/patch.jsfunction 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])// 調(diào)用VNode自身的insert鉤子函數(shù)}}}
再看insert鉤子:
constcomponentVNodeHooks={// init()insert(vnode:MountedComponentVNode){const{context,componentInstance}=vnodeif(!componentInstance._isMounted){componentInstance._isMounted=truecallHook(componentInstance,'mounted')}if(vnode.data.keepAlive){if(context._isMounted){queueActivatedComponent(componentInstance)}else{activateChildComponent(componentInstance,true/* direct */)}}// ...}}
在這個(gè)鉤子里面,調(diào)用了activateChildComponent函數(shù)遞歸地去執(zhí)行所有子組件的activated鉤子函數(shù):
// src/core/instance/lifecycle.jsexportfunctionactivateChildComponent(vm:Component,direct?:boolean){if(direct){vm._directInactive=falseif(isInInactiveTree(vm)){return}}elseif(vm._directInactive){return}if(vm._inactive||vm._inactive===null){vm._inactive=falsefor(leti=0;i<vm.$children.length;i++){activateChildComponent(vm.$children[i])}callHook(vm,'activated')}}
相反地枷莉,deactivated鉤子函數(shù)也是一樣的原理娇昙,在組件實(shí)例(VNode)的destroy鉤子函數(shù)中調(diào)用deactivateChildComponent函數(shù)。
參考