keepalive 是一种状态组件管理
他不是真正的组件不会被渲染
被keepalive包裹的组件只会在初次渲染的时候调用created和mounted,再次进入时,不再会被调用,只会调用actived等
应用场景:
在列表页进入详情页返回列表页想要保存搜索条件时可以结合路由和keepalive的设置
keepalive的原理是:
在created钩子函数里创建一个缓存函数,将节点缓存在里面 ,在需要重新渲染的时候再将vnode节点从cache对象中取出并渲染。在destroyed钩子则在组件被销毁的时候清除cache缓存中的所有组件实例
export default {
props: {
include: patternTypes, // 允许组件有条件地进行缓存
exclude: patternTypes,
max: [String, Number] // 最多可以缓存多少组件实例
},
created () {
this.cache = Object.create(null) // 创建一个cache对象,用来作为缓存容器,保存vnode节点
this.keys = []
},
destroyed () {
// 清除cache缓存中的所有组件实例
for (const key in this.cache) {
pruneCacheEntry(this.cache, key, this.keys)
}
},
}
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)
}