# 内置的组件
# keep-alive
# 什么是 keep-alive
引入
在开发中有这样一种情况,部分组件只需要初始化一次即可,下次展示时,将其缓存起来,将组件进行持久化,避免重复初始化。
keep-alive
是 Vue 的一个内置的组件,其作用就是进行组件缓存,也就是将其所包裹的组件保留状态,避免重复渲染。
# 基本用法
<!-- 使用 keep-alive 组件包裹需要进行缓存的组件 -->
<keep-alive>
<component><component>
</keep-alive>
1
2
3
4
2
3
4
解析
被包裹的组件在第一次进行完 mounted
钩子后,不会重新来过新一轮生命周期,当然不会重新渲染。
特殊情况
当非要使其重新渲染,使用两个特殊的钩子函数 activated
与 deactivated
activated
当keep-alive
包含的组件再次渲染的时候触发deactivated
当keep-alive
包含的组件销毁的时候触发
注意
被包含在 keep-alive
中的组件,会自动多出来这两个生命周期钩子
# 参数
keep-alive
有三个参数
include
字符串或正则表达式。只有名称匹配的组件会被缓存。exclude
字符串或正则表达式。任何名称匹配的组件都不会被缓存。max
数字。最多可以缓存多少组件实例。
注意
当使用正则表达式或者数组时,一定要使用v-bind
// 组件 a
export default {
name: 'ComponentA',
data () {
return {}
}
}
// B, C 组件不再赘述
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
<!-- 只缓存组件name为a或者b的组件 -->
<keep-alive include="ComponentA, ComponentB">
<ComponentA></ComponentA>
<ComponentB></ComponentB>
<!-- C 组件就被排除了,不缓存 -->
<ComponentC></ComponentC>
</keep-alive>
<!-- 组件 name 为 ComponentA 的组件不缓存(可以保留它的状态或避免重新渲染) -->
<keep-alive exclude="ComponentA"> a
<!-- A 组件不缓存 -->
<ComponentA></ComponentA>
<ComponentB></ComponentB>
<ComponentC></ComponentC>
</keep-alive>
<!-- 如果同时使用 include,exclude ,那么 exclude 优先于 include , 下面的例子只缓存 ComponentA 组件 -->
<keep-alive include="ComponentA, ComponentB" exclude="ComponentB">
<ComponentA></ComponentA>
<ComponentB></ComponentB>
</keep-alive>
<!-- 如果缓存的组件超过了 max 设定的值 5,那么将删除第一个缓存的组件 -->
<keep-alive exclude="c" max="5">
<component />
<!-- ... -->
</keep-alive>
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
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
注意
keep-alive
先匹配被包含组件的name
字段,如果name
不可用,则匹配当前组件components
配置中的注册名称。- 理解属性
exclude
:包含在keep-alive
中,但符合exclude
,不会调用activated
和deactivated
。 - 属性优先级:
include
与exclude
存在时,后者优先级大于前者。
# 与 vue-router 共同使用
router-view
也是一个组件,如果直接被包在 keep-alive
里面,所有路径匹配到的视图组件都会被缓存。
<keep-alive>
<router-view>
<!-- 所有路径匹配到的视图组件都会被缓存! -->
</router-view>
</keep-alive>
1
2
3
4
5
2
3
4
5
特殊情况
💯 对 router-view
中指定的组件进行缓存 💯
方案
你可能想到了,使用上面介绍的几个属性。
如下:
- 使用
include/exclude
- 使用
router.meta
属性
使用 include/exclude
// 组件 a
export default {
name: 'a',
data () {
return {}
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
<keep-alive include="a">
<router-view>
<!-- 只有路径匹配到的视图 a 组件会被缓存! -->
</router-view>
</keep-alive>
1
2
3
4
5
2
3
4
5
缺点
需要知道组件的 name,项目复杂的时候不是很好的选择
使用 router.meta
属性
// routes 配置
export default [
{
path: '/',
name: 'home',
component: Home,
meta: {
keepAlive: true // 需要被缓存
}
}, {
path: '/:id',
name: 'edit',
component: Edit,
meta: {
keepAlive: false // 不需要被缓存
}
}
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<keep-alive>
<router-view v-if="$route.meta.keepAlive">
<!-- 这里是会被缓存的视图组件,比如 Home! -->
</router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive">
<!-- 这里是不会被缓存的视图组件,比如 Profile! -->
</router-view>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9