什么是Keep-Alive?
<KeepAlive> 是一个内置组件,它的功能是在多个组件间动态切换时缓存被移除的组件实例。
<KeepAlive>缓存包裹在其中的动态切换组件。
<KeepAlive> 包裹动态组件时,会缓存不活跃的组件实例,而不是销毁它们。
基本用法
<KeepAlive>
<component :is="view"></component>
</KeepAlive>
包含/排除
<KeepAlive> 默认会缓存内部的所有组件实例,但我们可以通过 include (包含) 和 exclude(不包含) prop 来定制该行为。这两个 prop 的值都可以是一个以英文逗号分隔的字符串、一个正则表达式,或是包含这两种类型的一个数组:
<!-- 以英文逗号分隔的字符串 -->
<KeepAlive include="a,b">
<component :is="view" />
</KeepAlive>
<!-- 正则表达式 -->
<KeepAlive :include="/a|b/">
<component :is="view" />
</KeepAlive>
<!-- 数组 -->
<KeepAlive :include="['a', 'b']">
<component :is="view" />
</KeepAlive>
include and exclude 源码
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
}
它会根据组件的 name选项进行匹配,所以组件如果想要条件性地被 KeepAlive 缓存,就必须显式声明一个 name 选项。
最大缓存实例数
我们可以通过传入 max prop 来限制可被缓存的最大组件实例数。<KeepAlive> 的行为在指定了 max 后类似一个 LRU 缓存:如果缓存的实例数量即将超过指定的那个最大数量,则最久没有被访问的缓存实例将被销毁,以便为新的实例腾出空间。
如果超出最大缓存数的话,他会把第一个删掉,然后再向末尾进行添加。
LRU主体思想:如果这个组件最近被访问过,那么将来也会被访问。
<KeepAlive :max="10">
<component :is="activeComponent" />
</KeepAlive>
缓存实例的生命周期
当一个组件实例从 DOM 上移除但因为被 <KeepAlive> 缓存而仍作为组件树的一部分时,它将变为不活跃状态而不是被卸载。当一个组件实例作为缓存树的一部分插入到 DOM 中时,它将重新被激活。
一个持续存在的组件可以通过 activated 和 deactivated 选项来注册相应的两个状态的生命周期钩子:
export default {
activated() {
// 在首次挂载、
// 以及每次从缓存中被重新插入的时候调用
},
deactivated() {
// 在从 DOM 上移除、进入缓存
// 以及组件卸载时调用
}
}
Keep-Alive渲染源码
// 获取插槽的默认元素 this.$slots
const slot = this.$slots.default
// 获取第一个缓存的组件
const vnode: VNode = getFirstComponentChild(slot)
// 拿出当前组件的 options 选项
const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
if (componentOptions) {
// check pattern
// 获取组件名称
const name: ?string = getComponentName(componentOptions)
// 获取组件传过来的 props 包含 未包含
const { include, exclude } = this
if (
(include && (!name || !matches(include, name))) ||
(exclude && name && matches(exclude, name))
) {
return vnode
}
const { cache, keys } = this
const key: ?string = vnode.key == null
? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
: vnode.key
if (cache[key]) {
vnode.componentInstance = cache[key].componentInstance
// LRU 缓存淘汰算法
remove(keys, key)
keys.push(key)
} else {
// delay setting the cache until update
// 缓存当前的组件实例
this.vnodeToCache = vnode
// 缓存当前组件的 key
this.keyToCache = key
}
vnode.data.keepAlive = true
}
// 返回组件实例 返回插槽第一个元素
return vnode || (slot && slot[0])
}
文章内容:参考 vuejs官网