这是我参与8月更文挑战的第5天,活动详情查看:8月更文挑战node
keep-alive 是 Vue 内置的一个抽象组件,可使被包含的组件保留状态,即keep-alive 能够实现组件的缓存,当组件切换时不会对当前组件进行卸载。正则表达式
在组件切换过程当中将状态保留在内存中,防止重复渲染DOM,减小加载时间及性能消耗,提升用户体验性。缓存
通常结合路由和动态组件一块儿使用,用于缓存组件;markdown
提供 include 和 exclude 属性,二者都支持字符串或正则表达式, include 表示只有名称匹配的组件会被缓存,exclude 表示任何名称匹配的组件都不会被缓存 ,其中 exclude 的优先级比 include 高;函数
对应两个钩子函数 activated 和 deactivated ,当组件被激活时,触发钩子函数 activated,当组件被移除时,触发钩子函数 deactivated。post
props:性能
- include - 字符串或正则表达式。只有名称匹配的组件会被缓存。
- exclude - 字符串或正则表达式。任何名称匹配的组件都不会被缓存。
- max - 数字。最多能够缓存多少组件实例。
include和exclude属性是根据组件中的name属性来进行过滤的,而非路由中的name
复制代码
在 created 函数调用时将须要缓存的 VNode 节点保存在 this.cache 中/在 render(页面渲染) 时,若是 VNode 的 name 符合缓存条件(能够用 include 以及 exclude 控制),则会从 this.cache 中取出以前缓存的 VNode 实例进行渲染。ui
源码:core/components/keep-alive.js
this
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]) // 返回当前的虚拟节点
}
}
``
复制代码