概念
- keep-alive 是 vue 內(nèi)置的組件,用 keep-alive 包裹組件時(shí)霜运,會(huì)緩存不活動(dòng)的組件實(shí)例脾歇,而不是銷(xiāo)毀他們。主要用于保存組件狀態(tài)或避免重復(fù)創(chuàng)建(內(nèi)存換性能)
特點(diǎn)
- 它是一個(gè)抽象組件淘捡,自身不會(huì)渲染一個(gè) dom 元素藕各,也不會(huì)出現(xiàn)在組件的父組件鏈中
- 當(dāng)組件在 keep-alive 內(nèi)被切換,組件的
activated
和 deactivated
這兩個(gè)生命周期鉤子函數(shù)會(huì)被執(zhí)行案淋。組件一旦被緩存座韵,再次渲染就不會(huì)執(zhí)行 created
、mounted
生命周期鉤子函數(shù)
- 當(dāng)引入 keep-alive 的時(shí)候踢京,頁(yè)面第一次進(jìn)入誉碴,鉤子的觸發(fā)順序
created
> mounted
> activated
,退出時(shí)觸發(fā) deactivated
瓣距。當(dāng)再次進(jìn)入(前進(jìn)或者后退)時(shí)黔帕,只觸發(fā) activated
- 要求同時(shí)只有一個(gè)子組件被渲染
- 不會(huì)在函數(shù)式組件中正常工作,因?yàn)樗鼈儧](méi)有緩存實(shí)例
應(yīng)用
- 點(diǎn)擊列表頁(yè)進(jìn)入詳情頁(yè)后返回列表頁(yè)蹈丸,需要保留列表頁(yè)的篩選或者滾動(dòng)等操作不被重置
用法
- 在動(dòng)態(tài)組件中的應(yīng)用
<keep-alive :include="whiteList" :exclude="blackList" :max="amount">
<component :is="currentComponent"></component>
</keep-alive>
// whiteList 參數(shù)可以是數(shù)組形式成黄,也可以是字符串形式, ['a', 'b', 'c'] 或者 a,b,c(不能有空格)
// blackList 參數(shù)可以是數(shù)組形式逻杖,也可以是字符串形式奋岁, ['a', 'b', 'c'] 或者 a,b,c(不能有空格)
<keep-alive :include="whiteList" :exclude="blackList" :max="amount">
<router-view></router-view>
</keep-alive>
// whiteList 參數(shù)可以是數(shù)組形式,也可以是字符串形式荸百, ['a', 'b', 'c'] 或者 a,b,c(不能有空格)
// blackList 參數(shù)可以是數(shù)組形式闻伶,也可以是字符串形式, ['a', 'b', 'c'] 或者 a,b,c(不能有空格)
// 1. 在路由中的meta標(biāo)簽中記錄 keepAlive 的屬性為 true
{
path: '/shipTradingSale',
name: 'shipTradingSale',
component: () => import('@/views/shipTrading/sale'),
meta: {
title: '船舶出售',
keepAlive: true, // 開(kāi)啟緩存
}
}
// 2. 在創(chuàng)建router實(shí)例的時(shí)候加上scrollBehavior方法
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes,
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return {
x: 0,
y: 0
}
}
}
})
// 3. 在需要緩存的 router-view 組件上包裹 keep-alive 組件
<keep-alive>
<router-view v-if='$route.meta.keepAlive'></router-view>
</keep-alive><router-view v-if='!$route.meta.keepAlive'></router-view>
// 4. 動(dòng)態(tài)控制 keep-alive
beforeRouteLeave (to, from, next) {
this.loading = true
if (to.path === '/goodsDetails') {
from.meta.keepAlive = true
} else {
from.meta.keepAlive = false
}
next()
}
props
-
include
定義緩存白名單够话,只有名稱(chēng)匹配的組件會(huì)被緩存
-
exclude
定義緩存黑名單蓝翰,任何匹配的組件都不會(huì)被緩存
-
max
定義緩存組件上限光绕,超出上限使用 LRU的策略置換
緩存數(shù)據(jù)
渲染
- Vue的渲染是從 render 階段開(kāi)始的,但keep-alive的渲染是在patch階段畜份,這是構(gòu)建組件樹(shù)(虛擬DOM樹(shù))诞帐,并將VNode轉(zhuǎn)換成真正DOM節(jié)點(diǎn)的過(guò)程
原理
- 在
created
函數(shù)調(diào)用時(shí)將需要緩存的 VNode
節(jié)點(diǎn)保存在 this.cache
中,在 render
(頁(yè)面渲染) 時(shí)爆雹,如果 VNode
的 name
符合緩存條件(可以用 include 以及 exclude 控制)停蕉,則會(huì)從 this.cache
中取出之前緩存的 VNode 實(shí)例進(jìn)行渲染
源碼剖析
- 與定義組件的過(guò)程一樣,先是設(shè)置組件名為 keep-alive顶别,其次定義了一個(gè)
abstract
屬性谷徙,值為true
- props 屬性定義了 keep-alive 組件支持的全部參數(shù)
- keep-alive 在它生命周期內(nèi)定義了三個(gè)鉤子函數(shù)
created
初始化兩個(gè)對(duì)象分別緩存 VNode(虛擬DOM)和 VNode 對(duì)應(yīng)的鍵集合
destroyed
通過(guò)遍歷調(diào)用 pruneCacheEntry
函數(shù)刪除 this.cache
中緩存的VNode實(shí)例
mounted
對(duì) include
和 exclude
參數(shù)進(jìn)行監(jiān)聽(tīng),然后實(shí)時(shí)地更新(刪除)this.cache
對(duì)象數(shù)據(jù)驯绎。pruneCache
函數(shù)的核心也是去調(diào)用 pruneCacheEntry
// src/core/components/keep-alive.js
export default {
name: 'keep-alive',
abstract: true, // 判斷當(dāng)前組件虛擬dom是否渲染成真是dom的關(guān)鍵
props: {
include: patternTypes, // 緩存白名單
exclude: patternTypes, // 緩存黑名單
max: [String, Number] // 緩存的組件實(shí)例數(shù)量上限
},
created () {
this.cache = Object.create(null) // 緩存虛擬dom
this.keys = [] // 緩存的虛擬dom的健集合
},
destroyed () {
for (const key in this.cache) { // 刪除所有的緩存
pruneCacheEntry(this.cache, key, this.keys)
}
},
mounted () {
// 實(shí)時(shí)監(jiān)聽(tīng)黑白名單的變動(dòng)
this.$watch('include', val => {
pruneCache(this, name => matches(val, name))
})
this.$watch('exclude', val => {
pruneCache(this, name => !matches(val, name))
})
},
render () {
// 單獨(dú)拿出來(lái)
}
}
-
render
1、獲取 keep-alive 包裹著的第一個(gè)子組件對(duì)象及其組件名
2谋旦、根據(jù)設(shè)定的黑白名單(如果有)進(jìn)行條件匹配剩失,決定是否緩存。不匹配册着,直接返回組件實(shí)例(VNode)拴孤,否則執(zhí)行第 3 步
3、根據(jù)組件 ID 和 tag 生成緩存 Key甲捏,并在緩存對(duì)象中查找是否已緩存過(guò)該組件實(shí)例演熟。如果存在,直接取出緩存值并更新該 key 在 this.keys 中的位置(更新 key 的位置是實(shí)現(xiàn) LRU置換策略 的關(guān)鍵)司顿,否則執(zhí)行第 4 步
4芒粹、在 this.cache 對(duì)象中存儲(chǔ)該組件實(shí)例并保存key值,之后檢查緩存的實(shí)例數(shù)量是否超過(guò)max的設(shè)置值大溜,超過(guò)則根據(jù)LRU置換策略刪除最近最久未使用的實(shí)例(即是下標(biāo)為0的那個(gè)key)
5化漆、最后并且很重要,將該組件實(shí)例的 keepAlive 屬性值設(shè)置為 true钦奋。
// src/core/components/keep-alive.js
render () {
const slot = this.$slots.default
const vnode: VNode = getFirstComponentChild(slot) // 找到第一個(gè)子組件對(duì)象
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
const key: ?string = vnode.key == null // 定義組件的緩存key
// same constructor may get registered as different local components
// so cid alone is not enough (#3269)
? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
: vnode.key
if (cache[key]) { // 已經(jīng)緩存過(guò)該組件
vnode.componentInstance = cache[key].componentInstance
// make current key freshest
remove(keys, key)
keys.push(key) // 調(diào)整key排序
} else {
cache[key] = vnode // 緩存組件對(duì)象
keys.push(key)
// prune oldest entry
if (this.max && keys.length > parseInt(this.max)) { // 超過(guò)緩存數(shù)限制座云,將第一個(gè)刪除
pruneCacheEntry(cache, keys[0], keys, this._vnode)
}
}
vnode.data.keepAlive = true // 渲染和執(zhí)行被包裹組件的鉤子函數(shù)需要用到
}
return vnode || (slot && slot[0])
}