0%

【030】Vue选项:vue的生命周期钩子

什么是生命周期

vue 的每个组件就像一个生命体,有出生,有成长,有死亡等阶段,它们会在不同的阶段做不同的事,这个过程就是生命周期。

vue组件生命周期有以下几个:

周期 说明
beforeCreate 创建前
created 创建后
beforeMount 挂载前
mounted 挂载后
beforeUpdate 更新前
updated 更新后
beforeDestroy 销毁前
destroyed 销毁后

用法

示例代码:

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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
</head>
<body>
<div id="app">
<v-demo v-if="!isDestroy"></v-demo>
<button @click="isDestroy = true">销毁组件</button>
</div>
<script type="text/javascript">
// 先来定义一个组件
Vue.component('v-demo', {
data() {
return {
msg: '更新前'
}
},
template: `
<div>
<div>{{ msg }}</div>
<button @click="msg='更新后'">更新</button>
</div>
`,
// 以下是该组件的生命周期
beforeCreate() {
alert('创建前:beforeCreate');
},
created() {
alert('创建后:created');
},
beforeMount() {
alert('挂载前:beforeMount');
},
mounted() {
alert('挂载后:mounted');
},
beforeUpdate() {
alert('更新前:beforeUpdate');
},
updated() {
alert('更新后:updated');
},
beforeDestroy() {
alert('销毁前:beforeDestroy');
},
destroyed() {
alert('销毁后:destroyed');
}
})
var vm = new Vue({
el: '#app',
data() {
return {
isDestroy: false
}
}
})
</script>
</body>
</html>
  1. 在浏览器中运行上面的代码,页面一次弹出创建前:beforeCreate->创建后:created->挂载前:beforeMount->挂载后:mounted,这个就是vue组件其中一部分生命周期,那么怎么触发剩下的生命周期呢?
  2. 我们接着点击更新按钮,可以看到弹出更新前:beforeUpdate->更新后:updated,这个就像一个人遇到了某些事,然后作出某些反应一样。
  3. 最后来触发下销毁的生命周期,怎么触发呢?这个就好比人,生命走到尽头就什么都没有了,也就是说,我们只要把这个组件去掉就可以了,点击销毁组件按钮后依次弹出销毁前:beforeDestroy->销毁后:destroyed

总结

通过示例代码,是不是对生命周期有了比较直观的了解?其实在日常中,不论是开发还是面试,生命周期都是避不开的一个坎,大家一定要多敲几次熟悉一下。如果想具体了解,可以到官网选项 / 生命周期钩子查看,里面已经有详细的解释了,这里就不再多说。