keep-alive
keep-alive是Vue.js的一個內(nèi)置組件。它能夠不活動的組件實例保存在內(nèi)存中歉糜,而不是直接將其銷毀乘寒,它是一個抽象組件,不會被渲染到真實DOM中匪补,也不會出現(xiàn)在父組件鏈中伞辛。
它提供了include與exclude兩個屬性,允許組件有條件地進行緩存夯缺。
具體內(nèi)容可以參考官網(wǎng)蚤氏。
使用
用法
<keep-alive>
<component></component>
</keep-alive>
這里的component組件會被緩存起來。
舉個栗子
<keep-alive>
<coma v-if="test"></coma>
<comb v-else></comb>
</keep-alive>
<button @click="test=handleClick">請點擊</button>
export default {
data () {
return {
test: true
}
},
methods: {
handleClick () {
this.test = !this.test;
}
}
}
在點擊button時候踊兜,coma與comb兩個組件會發(fā)生切換竿滨,但是這時候這兩個組件的狀態(tài)會被緩存起來,比如說coma與comb組件中都有一個input標簽,那么input標簽中的內(nèi)容不會因為組件的切換而消失姐呐。
props
keep-alive組件提供了include與exclude兩個屬性來允許組件有條件地進行緩存殿怜,二者都可以用逗號分隔字符串、正則表達式或一個數(shù)組來表示曙砂。
<keep-alive include="a">
<component></component>
</keep-alive>
將緩存name為a的組件头谜。
<keep-alive exclude="a">
<component></component>
</keep-alive>
name為a的組件將不會被緩存。
生命鉤子
keep-alive提供了兩個生命鉤子鸠澈,分別是activated與deactivated柱告。
因為keep-alive會將組件保存在內(nèi)存中,并不會銷毀以及重新創(chuàng)建笑陈,所以不會重新調(diào)用組件的created等方法际度,需要用activated與deactivated這兩個生命鉤子來得知當前組件是否處于活動狀態(tài)。
深入keep-alive組件實現(xiàn)
說完了keep-alive組件的使用涵妥,我們從源碼角度看一下keep-alive組件究竟是如何實現(xiàn)組件的緩存的呢乖菱?
created與destroyed鉤子
created鉤子會創(chuàng)建一個cache對象,用來作為緩存容器蓬网,保存vnode節(jié)點窒所。
created () {
/* 緩存對象 */
this.cache = Object.create(null)
},
destroyed鉤子則在組件被銷毀的時候清除cache緩存中的所有組件實例。
/* destroyed鉤子中銷毀所有cache中的組件實例 */
destroyed () {
for (const key in this.cache) {
pruneCacheEntry(this.cache[key])
}
},
render
接下來是render函數(shù)帆锋。
render () {
/* 得到slot插槽中的第一個組件 */
const vnode: VNode = getFirstComponentChild(this.$slots.default)
const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
if (componentOptions) {
// check pattern
/* 獲取組件名稱吵取,優(yōu)先獲取組件的name字段,否則是組件的tag */
const name: ?string = getComponentName(componentOptions)
/* name不在inlcude中或者在exlude中則直接返回vnode(沒有取緩存) */
if (name && (
(this.include && !matches(this.include, name)) ||
(this.exclude && matches(this.exclude, name))
)) {
return vnode
}
const key: ?string = vnode.key == null
// 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
/* 如果已經(jīng)做過緩存了則直接從緩存中獲取組件實例給vnode锯厢,還未緩存過則進行緩存 */
if (this.cache[key]) {
vnode.componentInstance = this.cache[key].componentInstance
} else {
this.cache[key] = vnode
}
/* keepAlive標記位 */
vnode.data.keepAlive = true
}
return vnode
}
首先通過getFirstComponentChild獲取第一個子組件皮官,獲取該組件的name(存在組件名則直接使用組件名,否則會使用tag)实辑。接下來會將這個name通過include與exclude屬性進行匹配捺氢,匹配不成功(說明不需要進行緩存)則不進行任何操作直接返回vnode,vnode是一個VNode類型的對象剪撬,不了解VNode的同學可以參考筆者的另一篇文章《VNode節(jié)點》 .
/* 檢測name是否匹配 */
function matches (pattern: string | RegExp, name: string): boolean {
if (typeof pattern === 'string') {
/* 字符串情況讯沈,如a,b,c */
return pattern.split(',').indexOf(name) > -1
} else if (isRegExp(pattern)) {
/* 正則 */
return pattern.test(name)
}
/* istanbul ignore next */
return false
}
檢測include與exclude屬性匹配的函數(shù)很簡單,include與exclude屬性支持字符串如"a,b,c"這樣組件名以逗號隔開的情況以及正則表達式婿奔。matches通過這兩種方式分別檢測是否匹配當前組件。
if (this.cache[key]) {
vnode.componentInstance = this.cache[key].componentInstance
} else {
this.cache[key] = vnode
}
接下來的事情很簡單问慎,根據(jù)key在this.cache中查找萍摊,如果存在則說明之前已經(jīng)緩存過了,直接將緩存的vnode的componentInstance(組件實例)覆蓋到目前的vnode上面如叼。否則將vnode存儲在cache中冰木。最后返回vnode(有緩存時該vnode的componentInstance已經(jīng)被替換成緩存中的了)。
watch
用watch來監(jiān)聽pruneCache與pruneCache這兩個屬性的改變,在改變的時候修改cache緩存中的緩存數(shù)據(jù)踊沸。
watch: {
/* 監(jiān)視include以及exclude歇终,在被修改的時候?qū)ache進行修正 */
include (val: string | RegExp) {
pruneCache(this.cache, this._vnode, name => matches(val, name))
},
exclude (val: string | RegExp) {
pruneCache(this.cache, this._vnode, name => !matches(val, name))
}
},
來看一下pruneCache的實現(xiàn)。
/* 修正cache */
function pruneCache (cache: VNodeCache, current: VNode, filter: Function) {
for (const key in cache) {
/* 取出cache中的vnode */
const cachedNode: ?VNode = cache[key]
if (cachedNode) {
const name: ?string = getComponentName(cachedNode.componentOptions)
/* name不符合filter條件的逼龟,同時不是目前渲染的vnode時评凝,銷毀vnode對應(yīng)的組件實例(Vue實例),并從cache中移除 */
if (name && !filter(name)) {
if (cachedNode !== current) {
pruneCacheEntry(cachedNode)
}
cache[key] = null
}
}
}
}
/* 銷毀vnode對應(yīng)的組件實例(Vue實例) */
function pruneCacheEntry (vnode: ?VNode) {
if (vnode) {
vnode.componentInstance.$destroy()
}
}
遍歷cache中的所有項腺律,如果不符合filter指定的規(guī)則的話奕短,則會執(zhí)行pruneCacheEntry。pruneCacheEntry則會調(diào)用組件實例的$destroy方法來將組件銷毀匀钧。
最后
Vue.js內(nèi)部將DOM節(jié)點抽象成了一個個的VNode節(jié)點翎碑,keep-alive組件的緩存也是基于VNode節(jié)點的而不是直接存儲DOM結(jié)構(gòu)。它將滿足條件(pruneCache與pruneCache)的組件在cache對象中緩存起來之斯,在需要重新渲染的時候再將vnode節(jié)點從cache對象中取出并渲染日杈。