0%

【031】Vue选项:keep-alive的生命周期钩子

关于 keep-alive 组件

在开发时,经常会出现页签之类的组件,当在这些组件之间切换的时候,你有时会想保持这些组件的状态,以避免反复重渲染导致的性能问题。为了解决这个问题,我们可以用一个<keep-alive>元素将其动态组件包裹起来,从而在它们第一次被创建的时候缓存下来。

<keep-alive>包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。<keep-alive>是一个抽象组件:它自身不会渲染一个DOM元素,也不会出现在组件的父组件链中。

属性介绍

钩子在服务器端渲染期间不被调用。

当组件在<keep-alive>内被切换,它的 activated 和 deactivated 这两个生命周期钩子函数将会被对应执行。

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

模版代码:

1
2
3
<keep-alive :include="include" :exclude="exclude" :max="max">
<component :is="currentTab"></component>
</keep-alive>

属性的使用方法后期遇到了再讲解,在本章中主要看下生命周期钩子。

生命周期钩子函数的用法

周期 说明
activated 被 keep-alive 缓存的组件激活时调用
deactivated 被 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
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.btn {
padding: 5px 10px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
border: 1px solid #ddd;
cursor: pointer;
background-color: #fff;
margin-bottom: -1px;
margin-right: -1px;
}
.currentTab,
.btn:hover {
background-color: #ddd;
}
.btn:focus{
outline: 0;
}
.component {
padding: 10px 15px;
border: 1px solid #ddd;
width: 300px;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
</head>
<body>
<div id="app">
<div class="btns">
<button
class="btn"
:class="currentTab === item ? 'currentTab' : ''"
type="button"
v-for="(item, index) in tabs"
:key="index"
@click="currentTab = item"
>{{ item }}</button>
</div>
<keep-alive>
<component :is="currentTab"></component>
</keep-alive>
</div>
<script type="text/javascript">
Vue.component('tab01', {
template: `<div class="component">tab01<div>`,
activated() {
alert('activated = tab01');
},
deactivated() {
alert('deactivated = tab01');
}
})
Vue.component('tab02', {
template: `<div class="component">tab02<div>`,
activated() {
alert('activated = tab01');
},
deactivated() {
alert('deactivated = tab01');
}
})
var vm = new Vue({
el: '#app',
data() {
return {
tabs: ['tab01', 'tab02'],
currentTab: 'tab01'
}
}
})
</script>
</body>
</html>

运行上面的代码,过程就不再一一讲解了,都是一样的套路。