一.keep-alive的概念:
keep-alive实现对组件的缓存,当组件切换的过程中不会对当前组件进行卸载,keep-alive三个属性include/exclude以及max属性,常用的是include和exclude两个属性
- include - 字符串或正则表达式。只有名称匹配的组件会被缓存
- exclude - 字符串或正则表达式。任何名称匹配的组件都不会被缓存
- max - 数字。最多可以缓存多少组件实例
判断是否匹配成功 根据 include 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
}
修正缓存
function pruneCache (keepAliveInstance: any, filter: Function) {
// 当前 keep-alive 实例 缓存 key 数组 当前虚拟NODE
const { cache, keys, _vnode } = keepAliveInstance
// 对于不需要缓存的组件及时清除
for (const key in cache) {
const entry: ?CacheEntry = cache[key]
if (entry) {
const name: ?string = entry.name
if (name && !filter(name)) {
pruneCacheEntry(cache, key, keys, _vnode)
}
}
}
}
清除缓存
function pruneCacheEntry (
cache: CacheEntryMap,
key: string,
keys: Array<string>,
current?: VNode
) {
const entry: ?CacheEntry = cache[key]
// 如果缓存对象 没有实例或者 当前缓存的标签不等于当前标签
if (entry && (!current || entry.tag !== current.tag)) {
// 强制销毁
entry.componentInstance.$destroy()
}
// 清空
cache[key] = null
// 删除
remove(keys, key)
}
源码
export default {
name: 'keep-alive',
abstract: true, // 提取组件
props: {
include: patternTypes, // 包含
exclude: patternTypes, // 不包含
max: [String, Number] // 最大缓存数
},
methods: {
cacheVNode() {
// {} [] VNode key
const { cache, keys, vnodeToCache, keyToCache } = this
if (vnodeToCache) {
const { tag, componentInstance, componentOptions } = vnodeToCache
// 把当前缓存的对象挂到 cache 对象
cache[keyToCache] = {
name: getComponentName(componentOptions),
tag,
componentInstance,
}
// 把 key 添加到缓存 keys 数组里
keys.push(keyToCache)
// prune oldest entry
// 最大缓存数 keys 长度 大于 最大缓存数
// LRU 缓存淘汰算法
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode)
}
// 清除 vnodeToCache 这个变量
this.vnodeToCache = null
}
}
},
created () {
this.cache = Object.create(null) // {}
this.keys = [] // []
},
destroyed () {
for (const key in this.cache) {
pruneCacheEntry(this.cache, key, this.keys)
}
},
mounted () {
this.cacheVNode()
this.$watch('include', val => {
pruneCache(this, name => matches(val, name))
})
this.$watch('exclude', val => {
pruneCache(this, name => !matches(val, name))
})
},
updated () {
this.cacheVNode()
},
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
if (cache[key]) {
vnode.componentInstance = cache[key].componentInstance
// make current key freshest
remove(keys, key)
keys.push(key)
} else {
// delay setting the cache until update
this.vnodeToCache = vnode
this.keyToCache = key
}
vnode.data.keepAlive = true
}
return vnode || (slot && slot[0])
}
}
可以看到,它有3个属性,即有3个props。此外,它有created,destroyed,mounted,render四个钩子。
created和destroyed钩子
- created钩子会创建一个cache对象,用来作为缓存容器,保存vnode节点。
- destroyed钩子则在组件被销毁的时候清除cache缓存中的所有组件实例。
created () {
this.cache = Object.create(null) // {}
this.keys = [] // []
},
destroyed () {
for (const key in this.cache) {
pruneCacheEntry(this.cache, key, this.keys)
}
},
mounted钩子
在这个钩子函数里,调用了pruneCache方法,以观测 include 和 exclude 的变化。
mounted () {
this.cacheVNode()
this.$watch('include', val => {
pruneCache(this, name => matches(val, name))
})
this.$watch('exclude', val => {
pruneCache(this, name => !matches(val, name))
})
},
插槽
获取插槽的默认元素 this.$slots,获取缓存的组件,拿出当前的组件中options选项,获取组件名称,把组件传过来的props中include, exclude拿出来,然后使用LRU 缓存淘汰算法,缓存当前的组件实例,返回组件实例 返回插槽第一个元素
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
if (cache[key]) {
vnode.componentInstance = cache[key].componentInstance
// make current key freshest
remove(keys, key)
keys.push(key)
} else {
// delay setting the cache until update
this.vnodeToCache = vnode
this.keyToCache = key
}
vnode.data.keepAlive = true
}
return vnode || (slot && slot[0])
}
总结:Vue.js内部将DOM节点抽象成了一个个的VNode节点,keep-alive组件的缓存也是基于VNode节点的而不是直接存储DOM结构。它将满足条件的组件在cache对象中缓存起来,在需要重新渲染的时候再将vnode节点从cache对象中取出并渲染。