一、在首頁點擊一條數(shù)據(jù)進入詳情頁艰躺,按返回鍵返回首頁時頁面刷新了重新調(diào)用接口,用戶體驗比較差唤冈,不流暢,這里整理總結一下我的解決方案。。。
<keep-alive>是Vue的內(nèi)置組件嚼酝,能在組件切換過程中將狀態(tài)保留在內(nèi)存中浮还,防止重復渲染DOM。vue2.0提供了一個keep-alive組件用來緩存組件,避免多次加載相應的組件,減少性能消耗闽巩。
二钧舌、它有兩個生命周期:
- activated: keep-alive組件激活時調(diào)用
- deactivated: keep-alive組件停用時調(diào)用
它提供了include與exclude兩個屬性担汤,允許組件有條件地進行緩存。
三洼冻、實現(xiàn)原理
- 首先崭歧,你要知道Vue.js內(nèi)部將DOM節(jié)點抽象成了一個個的VNode節(jié)點,這個我之前寫過相關文章可以參考VNode節(jié)點撞牢。所以率碾,keep-alive的緩存也是基于VNode節(jié)點的而不是直接存儲DOM結構。
- 其實就是將需要緩存的VNode節(jié)點保存在this.cache中/在render時,如果VNode的name符合在緩存條件(可以用include以及exclude控制)屋彪,則會從this.cache中取出之前緩存的VNode實例進行渲染所宰。
keep-alive是Vue.js的一個內(nèi)置組件。它能夠不活動的組件實例保存在內(nèi)存中畜挥,而不是直接將其銷毀仔粥,它是一個抽象組件,不會被渲染到真實DOM中蟹但,也不會出現(xiàn)在父組件鏈中躯泰。
它提供了include與exclude兩個屬性,允許組件有條件地進行緩存华糖。
具體內(nèi)容可以參考官網(wǎng)麦向。
使用
用法
<keep-alive>
<component></component>
</keep-alive></pre>
這里的component組件會被緩存起來。
舉個栗子
<keep-alive>
<coma v-if="test"></coma>
<comb v-else="test"></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對應的組件實例(Vue實例)驰坊,并從cache中移除 */
if (name && !filter(name)) {
if (cachedNode !== current) {
pruneCacheEntry(cachedNode)
}
cache[key] = null
}
}
}
}
/* 銷毀vnode對應的組件實例(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結構舟扎。它將滿足條件(pruneCache與pruneCache)的組件在cache對象中緩存起來,在需要重新渲染的時候再將vnode節(jié)點從cache對象中取出并渲染悴务。