前言:
本篇主要內容來自以下文章
-
徹底揭祕keep-alive原理 https://github.com/qiudongwei/blog/issues/4 (此文的主要來源)
-
Vue源碼解析,keep-alive是如何實現緩存的? https://juejin.cn/post/6862206197877964807 (此文的主要來源)
-
keep-alive實現原理 https://www.jianshu.com/p/9523bb439950
-
http://blog.myweb.kim/vue/keep-alive/?utm-source=origin blog.myweb.kim/vue/keep-alive/?utm-source=origin
-
Vue.js 中,7種定義組件模板的方法 https://zhuanlan.zhihu.com/p/28073723
-
對於Vue組件的理解 https://www.jianshu.com/p/ce97328a9085
-
得物技術淺談Keep-alive 原理及業務解決方案 https://zhuanlan.zhihu.com/p/351499525
下文是上面這些文章的個人整理與總結,然後加上自己 標註(加粗、加色),以方便記憶。
在搭建 vue 項目時,有某些組件沒必要多次渲染,所以需要將組件在內存中進行‘持久化’,此時 <keep-alive> 便可以派上用場了。 <keep-alive> 可以使被包含的組件狀態維持不變,即便是組件切換了,其內的狀態依舊維持在內存之中。
前面整理過《vue keep-alive(1):vue router如何保證頁面回退頁面不刷新?,具體具體用法這裏不提,這裏來把keep-live 又彎掰直,深入 理解
keep-alive是什麼(基本概念宣講)
keep-alive是Vue的內置的一個抽象組件。
什麼是組件
組件系統是vue的另一個重要概念,它是一種抽象,允許我們使用小型、獨立和通常可複用的組件構建大型應用,因此,幾乎任意類型的應用界面都可以看成一個組件樹:
組件的作用既可以從父作用域將數據傳到子組件,也可以將把組件內部的數據發送到組件外部,可以實現互相傳送數據
7種定義組件模板的方法
-
字符串(String)
-
模板字符串(Template literal)
-
X-Templates
-
內聯(Inline)
-
Render函數(Render functions)
-
JSX
-
單文件組件(Single page components)
這知識舉例,一般都是用單文件組件
抽象組件
不會在DOM樹中渲染(真實或者虛擬都不會),不會渲染爲一個DOM元素,也不會出現在父組件鏈中——你永遠在 this.$parent 中找不到
它有一個屬性 abstract 爲 true,表明是它一個抽象組件
export default { name: 'abstractCompDemo', abstract: true, //標記爲抽象組件 }
這個特性,我就把當react的HOC 高階組件來用(不知道對不?)
抽象組件是如何忽略掉父子關係
Vue組件在初始化階段會調用 initLifecycle,裏面判斷父級是否爲抽象組件,如果是抽象組件,就選取抽象組件的上一級作爲父級,忽略與抽象組件和子組件之間的層級關係。
// 源碼位置: src/core/instance/lifecycle.js 32行 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 // ... }
如果 keep-alive 存在多個子元素,keep-alive 要求同時只有一個子元素被渲染。
keep-alive組件怎麼跳過生成DOM環節?
組件實例建立父子關係會根據abstract屬性決定是否忽略某個組件。在keep-alive中,設置了abstract: true,那Vue就會跳過該組件實例。
最後構建的組件樹中就不會包含keep-alive組件,那麼由組件樹渲染成的DOM樹自然也不會有keep-alive相關的節點了。
抽象組件代表:
<keep-alive>、<transition>、<transition-group>等組件
只需把封裝的功能 在組件外面包裹一層就夠了,這個用起來還是非常舒服的。比如節流、防抖、拖拽、權限控制等,都可以以這種形式去封裝。
keep-alive組件
keep-alive是一個抽象組件,使用keep-alive包裹動態組件時,會緩存不活動的組件實例,而不是銷燬它們。
keep-alive不僅僅是能夠保存頁面/組件的狀態這麼簡單,它還可以避免組件反覆創建和渲染,有效提升系統性能。總的來說,keep-alive用於保存組件的渲染狀態。
keep-alive props
-
include定義緩存白名單,keep-alive會緩存命中的組件;
-
exclude定義緩存黑名單,被命中的組件將不會被緩存;
-
max定義緩存組件上限,超出上限使用LRU的策略置換緩存數據。
LRU是內存管理的一種頁面置換算法。
LRU緩存策略
(Least recently used,最近最少使用)緩存策略:從內存中找出最久未使用的數據置換新的數據.算法根據數據的歷史訪問記錄來進行淘汰數據,其核心思想是如果數據最近被訪問過,那麼將來被訪問的機率也更高。
如果一個數據在最近一段時間沒有被訪問到,那麼在將來它被訪問的可能性也很小。也就是說,當限定的空間已存滿數據時,應當把最久沒有被訪問到的數據淘汰。
keep-alive 緩存機制便是根據LRU策略來設置緩存組件新鮮度,將很久未訪問的組件從緩存中刪除。
keep-alive源碼淺析
keep-alive.js內部還定義了一些工具函數,我們按住不動,先看它對外暴露的對象
// 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() { // 實時監聽黑白名單的變動 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的官方教程並未提及,卻至關重要,後面的渲染過程會用到。
在組件開頭就設置 abstract 爲 true,代表該組件是一個抽象組件。抽象組件,只對包裹的子組件做處理,並不會和子組件建立父子關係,也不會作爲節點渲染到頁面上。
props屬性定義了keep-alive組件支持的全部參數。
keep-alive在它生命週期內定義了三個鉤子函數:
created
初始化兩個對象分別緩存VNode(虛擬DOM)和VNode對應的鍵集合
destroyed
刪除this.cache中緩存的VNode實例。我們留意到,這不是簡單地將this.cache置爲null,而是遍歷調用pruneCacheEntry函數刪除。
// src/core/components/keep-alive.js 43行 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() // 執行組件的destroy鉤子函數 } cache[key] = null remove(keys, key) }
刪除緩存的VNode還要對應組件實例的destory鉤子函數
mounted
在mounted這個鉤子中對include和exclude參數進行監聽,然後實時地更新(刪除)this.cache對象數據。pruneCache函數的核心也是去調用pruneCacheEntry
pruneCache
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) } } }}
matches
判斷緩存規則,可以得知include與exclude,值類型可以是 字符串、正則表達式、數組
function matches (pattern: string | RegExp | Array<string>, name: string): boolean { if (Array.isArray(pattern)) { return pattern.indexOf(name) > -1 } else if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1 } else if (isRegExp(pattern)) { return pattern.test(name) } return false }
pruneCacheEntry
pruneCacheEntry 負責將組件從緩存中刪除,它會調用組件 $destroy 方法銷燬組件實例,緩存組件置空,並移除對應的 key。
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) } } } }
keep-alive 在 mounted 會監聽 include 和 exclude 的變化,屬性發生改變時調整緩存和 keys 的順序,最終調用的也是 pruneCacheEntry。
render
render是核心,所以放在最後講。簡要來說,keep-alive 是由 render 函數決定渲染結果。
在開頭會獲取插槽內的子元素,調用 getFirstComponentChild 獲取到第一個子元素的 VNode——如果 keep-alive 存在多個子元素,keep-alive 要求同時只有一個子元素被渲染。所以在開頭會獲取插槽內的子元素,調用 getFirstComponentChild 獲取到第一個子元素的 VNode。
接着判斷當前組件是否符合緩存條件,組件名與 include 不匹配或與 exclude 匹配都會直接退出並返回 VNode,不走緩存機制。
匹配條件通過會進入緩存機制的邏輯,如果命中緩存,從 cache 中獲取緩存的實例設置到當前的組件上,並調整 key 的位置將其放到最後(LRU 策略)。如果沒命中緩存,將當前 VNode 緩存起來,並加入當前組件的 key。如果緩存組件的數量超出 max 的值,即緩存空間不足,則調用 pruneCacheEntry 將最舊的組件從緩存中刪除,即 keys[0] 的組件。之後將組件的 keepAlive 標記爲 true,表示它是被緩存的組件。
render () { const slot = this.$slots.defalut const vnode: VNode = getFirstComponentChild(slot) // 找到第一個子組件對象 const componentOptions : ?VNodeComponentOptions = vnode && vnode.componentOptions if (componentOptions) { // 存在組件參數 // 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]) { // 已經緩存過該組件 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)) { //超過緩存數限制,將第一個刪除 pruneCacheEntry(cahce, keys[0], keys, this._vnode) } } vnode.data.keepAlive = true //渲染和執行被包裹組件的鉤子函數需要用到 } return vnode || (slot && slot[0]) }
總結:
-
獲取keep-alive包裹着的第一個子組件對象及其組件名;
-
如果 keep-alive 存在多個子元素,keep-alive 要求同時只有一個子元素被渲染。所以在開頭會獲取插槽內的子元素,調用 getFirstComponentChild 獲取到第一個子元素的 VNode。
-
-
根據設定的黑白名單(如果有)進行條件匹配,決定是否緩存。不匹配,直接返回組件實例(VNode),否則執行第三步;
-
根據組件ID和tag生成緩存Key,並在緩存對象中查找是否已緩存過該組件實例。如果存在,直接取出緩存值並更新該key在this.keys中的位置(更新key的位置是實現LRU置換策略的關鍵),否則執行第四步;
-
在this.cache對象中存儲該組件實例並保存key值,之後檢查緩存的實例數量是否超過max設置值,超過則根據LRU置換策略刪除最近最久未使用的實例(即是下標爲0的那個key)
-
最後並且很重要,將該組件實例的keepAlive屬性值設置爲true。
Vue的渲染過程中keep-live分析
藉助一張圖看下Vue渲染的整個過程:
概括來說
VNode構建完成後,最終會被轉換成真實dom,而 patch 是必經的過程。
Vue的渲染是從圖中render階段開始的,但keep-alive的渲染是在patch階段,這是構建組件樹(虛擬DOM樹),並將VNode轉換成真正DOM節點的過程。
簡單描述從render到patch的過程
我們從最簡單的new Vue開始:
import App from './App.vue' new Vue({render: h => h(App)}).$mount('#app')
-
Vue在渲染的時候先調用原型上的_render函數將組件對象轉化成一個VNode實例;而_render是通過調用createElement和createEmptyVNode兩個函數進行轉化;
-
createElement的轉化過程會根據不同的情形選擇new VNode或者調用createComponent函數做VNode實例化;
-
完成VNode實例化後,這時候Vue調用原型上的_update函數把VNode渲染成真實DOM,這個過程又是通過調用patch函數完成的(這就是patch階段了)
用一張圖表達:
keep-alive包裹的組件是如何使用緩存的?
在patch階段,會執行createComponent函數:
// src/core/vdom/patch.js 210行 function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { let i = vnode.data if (isDef(i)) { // isReactivated 標識組件是否重新激活 isDef =(v)=>v !== undefined && v !== null const isReactivated = isDef(vnode.componentInstance) && i.keepAlive if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */) } // 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.elm 賦值爲真實dom initComponent(vnode, insertedVnodeQueue) // insert 將組件的真實dom插入到父元素中。 insert(parentElm, vnode.elm, refElm) if (isTrue(isReactivated)) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm) } return true } } }
-
在首次加載被包裹組件時,組件還沒有初始化構造完成,vnode.componentInstance的值是undefined,keepAlive的值是true。因此isReactivated值爲false。因爲keep-alive組件作爲父組件,它的render函數會先於被包裹組件執行;那麼就只執行到i(vnode, false /* hydrating */),後面的邏輯不再執行;
-
再次訪問被包裹組件時,vnode.componentInstance的值就是已經緩存的組件實例,那麼會執行insert(parentElm, vnode.elm, refElm)邏輯,這樣就直接把上一次的DOM插入到了父元素中。
init 函數
init 函數進行組件初始化,它是組件的一個鉤子函數:
// 源碼位置:src/core/vdom/create-component.js const componentVNodeHooks = { init (vnode: VNodeWithData, hydrating: boolean): ?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 ) child.$mount(hydrating ? vnode.elm : undefined, hydrating) } }, // ... }
createComponentInstanceForVnode 內會 new Vue 構造組件實例並賦值到 componentInstance,隨後調用 $mount 掛載組件。
reactivateComponent
function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) { let i // hack for #4339: a reactivated component with inner transition // does not trigger because the inner node's created hooks are not called // again. It's not ideal to involve module-specific logic in here but // there doesn't seem to be a better way to do it. let innerNode = vnode while (innerNode.componentInstance) { innerNode = innerNode.componentInstance._vnode if (isDef(i = innerNode.data) && isDef(i = i.transition)) { for (i = 0; i < cbs.activate.length; ++i) { cbs.activate[i](emptyNode, innerNode) } insertedVnodeQueue.push(innerNode) break } } // unlike a newly created component, // a reactivated keep-alive component doesn't insert itself insert(parentElm, vnode.elm, refElm) } function insert (parent, elm, ref) { if (isDef(parent)) { if (isDef(ref)) { if (nodeOps.parentNode(ref) === parent) { nodeOps.insertBefore(parent, elm, ref) } } else { nodeOps.appendChild(parent, elm) } } }
所以在初始化渲染中,keep-alive 將A組件緩存起來,然後正常的渲染A組件。
緩存渲染
當切換到B組件,再切換回A組件時,A組件命中緩存被重新激活。
再次經歷 patch 過程,keep-alive 是根據插槽獲取當前的組件,那麼插槽的內容又是如何更新實現緩存?
// src/core/vdom/patch.js 714行 const isRealElement = isDef(oldVnode.nodeType) if (!isRealElement && sameVnode(oldVnode, vnode)) { // patch existing root node patchVnode(oldVnode, vnode, insertedVnodeQueue, null, null, removeOnly) }
非初始化渲染時,patch 會調用 patchVnode 對比新舊節點。
// 源碼位置:src/core/vdom/patch.js function patchVnode ( oldVnode, vnode, insertedVnodeQueue, ownerArray, index, removeOnly ) { // ... let i const data = vnode.data if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) { i(oldVnode, vnode) } // ...
patchVnode 內會調用鉤子函數 prepatch。
// 源碼位置: src/core/vdom/create-component.js prepatch (oldVnode: MountedComponentVNode, vnode: MountedComponentVNode) { const options = vnode.componentOptions const child = vnode.componentInstance = oldVnode.componentInstance updateChildComponent( child, options.propsData, // updated props options.listeners, // updated listeners vnode, // new parent vnode options.children // new children ) },
updateChildComponent 就是更新的關鍵方法,它裏面主要是更新實例的一些屬性:
// 源碼位置:src/core/instance/lifecycle.js export function updateChildComponent ( vm: Component, propsData: ?Object, listeners: ?Object, parentVnode: MountedComponentVNode, renderChildren: ?Array<VNode> ) { // ... // Any static slot children from the parent may have changed during parent's // update. Dynamic scoped slots may also have changed. In such cases, a forced // update is necessary to ensure correctness. const needsForceUpdate = !!( renderChildren || // has new static slots vm.$options._renderChildren || // has old static slots hasDynamicScopedSlot ) // ... // resolve slots + force update if has children if (needsForceUpdate) { vm.$slots = resolveSlots(renderChildren, parentVnode.context) vm.$forceUpdate() } } Vue.prototype.$forceUpdate = function () { const vm: Component = this if (vm._watcher) { // 這裏最終會執行 vm._update(vm._render) vm._watcher.update() } }
從註釋中可以看到 needsForceUpdate 是有插槽纔會爲 true,keep-alive 符合條件。首先調用 resolveSlots 更新 keep-alive 的插槽,然後調用 $forceUpdate 讓 keep-alive 重新渲染,再走一遍 render。因爲A組件在初始化已經緩存了,keep-alive 直接返回緩存好的A組件 VNode。VNode 準備好後,又來到了 patch 階段。
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 */) } // 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) insert(parentElm, vnode.elm, refElm) if (isTrue(isReactivated)) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm) } return true } } }
A組件再次經歷 createComponent 的過程,調用 init。
const componentVNodeHooks = { init (vnode: VNodeWithData, hydrating: boolean): ?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 ) child.$mount(hydrating ? vnode.elm : undefined, hydrating) } }, }
這時將不再走 $mount 的邏輯,只調用 prepatch 更新實例屬性。所以在緩存組件被激活時,不會執行 created 和 mounted 的生命週期函數。
回到 createComponent,此時的 isReactivated 爲 true,調用 reactivateComponent:
function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) { let i // hack for #4339: a reactivated component with inner transition // does not trigger because the inner node's created hooks are not called // again. It's not ideal to involve module-specific logic in here but // there doesn't seem to be a better way to do it. let innerNode = vnode while (innerNode.componentInstance) { innerNode = innerNode.componentInstance._vnode if (isDef(i = innerNode.data) && isDef(i = i.transition)) { for (i = 0; i < cbs.activate.length; ++i) { cbs.activate[i](emptyNode, innerNode) } insertedVnodeQueue.push(innerNode) break } } // unlike a newly created component, // a reactivated keep-alive component doesn't insert itself insert(parentElm, vnode.elm, refElm) }
最後調用 insert 插入組件的dom節點,至此緩存渲染流程完成。
keep-live鉤子函數
一般的組件,每一次加載都會有完整的生命週期,即生命週期裏面對應的鉤子函數都會被觸發,爲什麼被keep-alive包裹的組件卻不是呢?
只執行一次鉤子函數
一般的組件,每一次加載都會有完整的生命週期,即生命週期裏面對應的鉤子函數都會被觸發,爲什麼被keep-alive包裹的組件卻不是呢?
因爲被緩存的組件實例會爲其設置keepAlive = true,而在初始化組件鉤子函數中:
// src/core/vdom/create-component.js const componentVNodeHooks = { init (vnode: VNodeWithData, hydrating: boolean): ?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 ) child.$mount(hydrating ? vnode.elm : undefined, hydrating) } } // ... }
可以看出,當vnode.componentInstance和keepAlive同時爲truly值時,不再進入$mount過程,那mounted之前的所有鉤子函數(beforeCreate、created、mounted)都不再執行。
可重複的activated
在patch的階段,最後會執行invokeInsertHook函數,而這個函數就是去調用組件實例(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鉤子函數 } } }
再看insert鉤子:
// src/core/vdom/create-component.js 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函數遞歸地去執行所有子組件的activated鉤子函數:
// 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鉤子函數也是一樣的原理,在組件實例(VNode)的destroy鉤子函數中調用deactivateChildComponent函數。