keep-alive是Vue.js的一個內置組件。<keep-alive> 包裹動態組件時,會緩存不活動的組件實例,而不是銷燬它們。它自身不會渲染一個 DOM 元素,也不會出如今父組件鏈中。 當組件在 <keep-alive> 內被切換,它的 activated 和 deactivated 這兩個生命週期鉤子函數將會被對應執行。 它提供了include與exclude兩個屬性,容許組件有條件地進行緩存。html
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
複製代碼
在點擊button時候,兩個input會發生切換,可是這時候這兩個輸入框的狀態會被緩存起來,input標籤中的內容不會由於組件的切換而消失。vue
* include - 字符串或正則表達式。只有匹配的組件會被緩存。
* exclude - 字符串或正則表達式。任何匹配的組件都不會被緩存。
複製代碼
<keep-alive include="a">
<component></component>
</keep-alive>
複製代碼
只緩存組件別民name爲a的組件node
<keep-alive exclude="a">
<component></component>
</keep-alive>
複製代碼
除了name爲a的組件,其餘都緩存下來正則表達式
生命鉤子 keep-alive提供了兩個生命鉤子,分別是activated與deactivated。數組
由於keep-alive會將組件保存在內存中,並不會銷燬以及從新建立,因此不會從新調用組件的created等方法,須要用activated與deactivated這兩個生命鉤子來得知當前組件是否處於活動狀態。緩存
created鉤子會建立一個cache對象,用來做爲緩存容器,保存vnode節點。bash
props: {
include: patternTypes,
exclude: patternTypes,
max: [String, Number]
},
created () {
// 建立緩存對象
this.cache = Object.create(null)
// 建立一個key別名數組(組件name)
this.keys = []
},
複製代碼
destroyed鉤子則在組件被銷燬的時候清除cache緩存中的全部組件實例。函數
destroyed () {
/* 遍歷銷燬全部緩存的組件實例*/
for (const key in this.cache) {
pruneCacheEntry(this.cache, key, this.keys)
}
},
複製代碼
:::demoui
render () {
/* 獲取插槽 */
const slot = this.$slots.default
/* 根據插槽獲取第一個組件組件 */
const vnode: VNode = getFirstComponentChild(slot)
const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
if (componentOptions) {
// 獲取組件的名稱(是否設置了組件名稱name,沒有則返回組件標籤名稱)
const name: ?string = getComponentName(componentOptions)
// 解構對象賦值常量
const { include, exclude } = this
if ( /* name不在inlcude中或者在exlude中則直接返回vnode */
// 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
// 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]) { // 判斷當前是否有緩存,有則取緩存的實例,無則進行緩存
vnode.componentInstance = cache[key].componentInstance
// make current key freshest
remove(keys, key)
keys.push(key)
} else {
cache[key] = vnode
keys.push(key)
// 判斷是否設置了最大緩存實例數量,超過則刪除最老的數據,
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode)
}
}
// 給vnode打上緩存標記
vnode.data.keepAlive = true
}
return vnode || (slot && slot[0])
}
// 銷燬實例
function pruneCacheEntry ( cache: VNodeCache, key: string, keys: Array<string>, current?: VNode ) {
const cached = cache[key]
if (cached && (!current || cached.tag !== current.tag)) {
cached.componentInstance.$destroy()
}
cache[key] = null
remove(keys, 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)
// 組件name 不符合filler條件, 銷燬實例,移除cahe
if (name && !filter(name)) {
pruneCacheEntry(cache, key, keys, _vnode)
}
}
}
}
// 篩選過濾函數
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)
}
/* istanbul ignore next */
return false
}
// 檢測 include 和 exclude 數據的變化,實時寫入讀取緩存或者刪除
mounted () {
this.$watch('include', val => {
pruneCache(this, name => matches(val, name))
})
this.$watch('exclude', val => {
pruneCache(this, name => !matches(val, name))
})
},
複製代碼
:::this
經過查看Vue源碼能夠看出,keep-alive默認傳遞3個屬性,include 、exclude、max, max 最大可緩存的長度
<!--exclude - 字符串或正則表達式。任何匹配的組件都不會被緩存。-->
<!--TODO 匹配首先檢查組件自身的 name 選項,若是 name 選項不可用,則匹配它的局部註冊名稱-->
<keep-alive :exclude="keepAliveConf.value">
<router-view class="child-view" :key="$route.fullPath"></router-view>
</keep-alive>
<!-- 或者 -->
<keep-alive :include="keepAliveConf.value">
<router-view class="child-view" :key="$route.fullPath"></router-view>
</keep-alive>
<!-- 具體使用 include 仍是exclude 根據項目是否須要緩存的頁面數量多少來決定-->
複製代碼
建立一個keepAliveConf.js 放置須要匹配的組件名
// 路由組件命名集合
var arr = ['component1', 'component2'];
export default {value: routeList.join()};
複製代碼
配置重置緩存的全局方法
import keepAliveConf from 'keepAliveConf.js'
Vue.mixin({
methods: {
// 傳入須要重置的組件名字
resetKeepAive(name) {
const conf = keepAliveConf.value;
let arr = keepAliveConf.value.split(',');
if (name && typeof name === 'string') {
let i = arr.indexOf(name);
if (i > -1) {
arr.splice(i, 1);
keepAliveConf.value = arr.join();
setTimeout(() => {
keepAliveConf.value = conf
}, 500);
}
}
},
}
})
複製代碼