用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- 逗号分隔字符串 -->
<keep-alive include="a,b">
<component :is="view"></component>
</keep-alive>

<!-- 正则表达式 (使用 `v-bind`) -->
<keep-alive :include="/a|b/">
<component :is="view"></component>
</keep-alive>

<!-- 数组 (使用 `v-bind`) -->
<keep-alive :include="['a', 'b']">
<component :is="view"></component>
</keep-alive>

属性

  • include: 字符串或正则表达式。只有名称匹配的组件会被缓存
  • exclude: 字符串或正则表达式。任何名称匹配的组件都不会被缓存
  • max: 数字。最多可以缓存多少组件实例

规则

  • 匹配时首先检查组件自身的 name 选项,如果 name 选项不可用,则匹配它的局部注册名称 (父组件 components 选项的键值),也就是组件的标签值。匿名组件不能被匹配
  • max 表示最多可以缓存多少组件实例。一旦这个数字达到了,在新实例被创建之前,已缓存组件中最久没有被访问的实例会被销毁掉 (LRU)
  • <keep-alive> 只处理第一个子元素,所以一般和它搭配使用的有 component 动态组件或者是 router-view

删除缓存组件并且为什么命中缓存了需要调整组件 key 的顺序:
缓存淘汰策略 LRU (Least recently used,最近最少使用) ,如果数据最近被访问过,那么将来被访问的几率也更高

生命周期钩子

  • 组件一旦被 <keep-alive> 缓存,那么再次渲染的时候就不会执行 created、mounted 等钩子函数
  • activated 和 deactivated,执行时机是 <keep-alive> 包裹的组件激活时调用和停用时调用

LRU

缓存机制

  • 将新数据从尾部插入到 this.keys 中
  • 每当缓存命中 (即缓存数据被访问),则将数据移到 this.keys 的尾部
  • 当 this.keys 满的时候,将头部的数据丢弃

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// 函数式组件,执行 <keep-alive> 组件渲染的时候,就会执行 render 函数
() => ({
name: 'keep-alive',
abstract: true,

props: {
include: [String, RegExp, Array],
exclude: [String, RegExp, Array],
max: [String, Number]
},

created () {
this.cache = Object.create(null) // 存储需要缓存的组件,this.cache = { 'key1':'组件1', 'key2':'组件2', // ... }
this.keys = [] // 存储每个需要缓存的组件的key,即对应this.cache对象中的键值
},

destroyed () {
// 将那些被缓存的并且当前没有处于被渲染状态的组件都销毁掉并将其从this.cache对象中剔除
for (const key in this.cache) {
pruneCacheEntry(this.cache, key, this.keys)
}
},

// pruneCacheEntry函数
pruneCacheEntry (cache,key,keys,current) {
const cached = cache[key]
/* 判断当前没有处于被渲染状态的组件,将其销毁*/
if (cached && (!current || cached.tag !== current.tag)) {
cached.componentInstance.$destroy()
}
cache[key] = null
remove(keys, key)
},

// 如果include 或exclude 发生了变化,即表示定义需要缓存的组件的规则或者不需要缓存的组件的规则发生了变化,那么就执行pruneCache函数
mounted () {
this.$watch('include', val => {
pruneCache(this, name => matches(val, name))
})
this.$watch('exclude', val => {
pruneCache(this, name => !matches(val, name))
})
},

// 该函数内对this.cache对象进行遍历,取出每一项的name值,用其与新的缓存规则进行匹配,如果匹配不上,则表示在新的缓存规则下该组件已经不需要被缓存,
// 则调用pruneCacheEntry函数将这个已经不需要缓存的组件实例先销毁掉,然后再将其从this.cache对象中剔除
pruneCache (keepAliveInstance, filter) {
const { cache, keys, _vnode } = keepAliveInstance
for (const key in cache) {
const cachedNode = cache[key]
if (cachedNode) {
const name = getComponentName(cachedNode.componentOptions)
if (name && !filter(name)) {
pruneCacheEntry(cache, key, keys, _vnode)
}
}
}
},

pruneCacheEntry (cache,key,keys,current) {
const cached = cache[key]
if (cached && (!current || cached.tag !== current.tag)) {
cached.componentInstance.$destroy()
}
cache[key] = null
remove(keys, key)
},

render() {
/* 获取默认插槽中的第一个组件节点 */
const slot = this.$slots.default
const vnode = getFirstComponentChild(slot)
/* 获取该组件节点的componentOptions */
const componentOptions = vnode && vnode.componentOptions

if (componentOptions) {
/* 获取该组件节点的名称,优先获取组件的name字段,如果name不存在则获取组件的tag */
const name = getComponentName(componentOptions)
/* 优先获取组件的name字段,如果name不存在则获取组件的tag */
function getComponentName (opts) {
return opts && (opts.Ctor.options.name || opts.tag)
}

const { include, exclude } = this
/* 如果name不在inlcude中或者存在于exlude中则表示不缓存,直接返回vnode */
if (
(include && (!name || !matches(include, name))) ||
// excluded
(exclude && name && matches(exclude, name))
) {
return vnode
}

const { cache, keys } = this
/* 获取组件的key */
const key = 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
/* 如果命中缓存,则直接从缓存中拿 vnode 的组件实例 */
if (cache[key]) {
vnode.componentInstance = cache[key].componentInstance
/* 调整该组件key的顺序,将其从原来的地方删掉并重新放在最后一个 */
remove(keys, key)
keys.push(key)
}
/* 如果没有命中缓存,则将其设置进缓存 */
else {
cache[key] = vnode
keys.push(key)
/* 如果配置了max并且缓存的长度超过了this.max,则从缓存中删除第一个 */
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode)
}
}

/* 最后设置keepAlive标记位 */
vnode.data.keepAlive = true
}
return vnode || (slot && slot[0])
}
})