介绍
keep-alive是Vue.js的一个内置组件。它会缓存不活动的组件实例,而不是直接将其销毁,它是一个抽象组件,不会被渲染到真实DOM中,也不会出现在父组件链中。它提供了include与exclude属性,允许组件有条件地进行缓存,其中exclude的优先级比include高,max最多可以缓存多少组件实例。
钩子函数
对应两个钩子函数 activated 和 deactivated ,当组件被激活时,触发钩子函数 activated,当组件被移除时,触发钩子函数 deactivated。
原理
在created钩子会创建一个cache对象,用来作为缓存容器,保存vnode节点。在需要重新渲染的时候再将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)
}