这是我参与8月更文挑战的第5天,活动详情查看:8月更文挑战
概念
keep-alive 是 Vue 内置的一个抽象组件,可以使被包含的组件保留状态,即keep-alive 可以实现组件的缓存,当组件切换时不会对当前组件进行卸载。
作用
在组件切换过程中将状态保留在内存中,防止重复渲染DOM,减少加载时间及性能消耗,提高用户体验性。
理解
-
一般结合路由和动态组件一起使用,用于缓存组件;
-
提供 include 和 exclude 属性,两者都支持字符串或正则表达式, include 表示只有名称匹配的组件会被缓存,exclude 表示任何名称匹配的组件都不会被缓存 ,其中 exclude 的优先级比 include 高;
-
对应两个钩子函数 activated 和 deactivated ,当组件被激活时,触发钩子函数 activated,当组件被移除时,触发钩子函数 deactivated。
props:
- include – 字符串或正则表达式。只有名称匹配的组件会被缓存。
- exclude – 字符串或正则表达式。任何名称匹配的组件都不会被缓存。
- max – 数字。最多可以缓存多少组件实例。
include和exclude属性是根据组件中的name属性来进行过滤的,而非路由中的name
复制代码
原理
在 created 函数调用时将需要缓存的 VNode 节点保存在 this.cache 中/在 render(页面渲染) 时,如果 VNode 的 name 符合缓存条件(可以用 include 以及 exclude 控制),则会从 this.cache 中取出之前缓存的 VNode 实例进行渲染。
源码:core/components/keep-alive.js
export default {
name: 'keep-alive',
abstract: true, // 抽象组件
props: {
include: patternTypes,
exclude: patternTypes,
max: [String, Number]
},
created() {
this.cache = Object.create(null) // 创建缓存列表
this.keys = [] // 创建缓存组件的key列表
},
destroyed() { // keep-alive销毁时 会清空所有的缓存和key
for (const key in this.cache) { // 循环销毁
pruneCacheEntry(this.cache, key, this.keys)
}
},
mounted() { // 会监控include 和 exclude属性 进行组件的缓存处理
this.$watch('include', val => {
pruneCache(this, name => matches(val, name))
}) this.$watch('exclude', val => {
pruneCache(this, name => !matches(val, name))
})
},
render() {
const slot = this.$slots.default // 会默认拿插槽
const vnode: VNode = getFirstComponentChild(slot) // 只缓存第一个组件
const componentOptions: ? VNodeComponentOptions = vnode && vnode.componentOptions
if (componentOptions) { // check pattern
const name: ? string = getComponentName(componentOptions) // 取出组件的名字
const {
include,
exclude
} = this
if ( // 判断是否缓存
// 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, // 如果组件没key 就自己通过 组件的标签和key和cid 拼接一个key
if (cache[key]) {
vnode.componentInstance = cache[key].componentInstance // 直接拿到组件实 例
// make current key freshest
remove(keys, key) // 删除当前的 [b,c,d,e,a]
// LRU 最近最久未使用法
keys.push(key) // 并将key放到后面[b,a]
} else {
cache[key] = vnode // 缓存vnode
keys.push(key) // 将key 存入
// prune oldest entry
if (this.max && keys.length > parseInt(this.max)) {
// 缓存的太多超过了max 就需要删除掉
pruneCacheEntry(cache, keys[0], keys, this._vnode)
// 要删除第0个 但是现 在渲染的就是第0个
}
}
vnode.data.keepAlive = true // 并且标准keep-alive下的组件是一个缓存组件
}
return vnode || (slot && slot[0]) // 返回当前的虚拟节点
}
}
``
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END