目录
2.2 beforeCreate和created钩子函数间的生命周期
2.3 created钩子函数和beforeMount间的生命周期
2.4 beforeMount和mounted钩子函数间的生命周期
2.5 beforeUpdate钩子函数和updated钩子函数间的生命周期
2.6 beforeDestroy和destroyed钩子函数间的生命周期
一、 生命周期图
Vue实例的生命周期中有多个状态。
测试代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="root">
</div>
</body>
<script type="text/javascript" src="./vue.js"></script>
<script type="text/javascript">
var vm = new Vue({
el : '#root',
data(){
return{
msg:"111"
}
},
template:'<div>{
{msg}}</div>',
beforeCreate:function(){
console.log('beforeCreate');
},
created:function(){
console.log('created');
},
beforeMount:function(){
console.log(this.$el);
console.log('beforeMount');
},
mounted:function(){
console.log(this.$el);
console.log('Mount');
},
beforeUpdate(){
console.log("调用了beforeUpdate钩子函数");
},
updated(){
console.log("调用了Update钩子函数");
},
beforeDestroy(){
console.log("调用了beforeDestroy钩子函数");
},
destroyed(){
console.log("调用了destroyed钩子函数");
},
})
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue实例的生命周期</title>
</head>
<body>
<div id="app">
<h1>测试生命周期</h1>
<div>{
{msg}}</div>
<hr>
<h3>测试beforeUpdate和update两个钩子函数</h3>
<button @click="handlerUpdate">更新数据</button>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
msg: "12345"
},
methods: {
handlerUpdate() {
this.msg=this.msg.split("").reverse().join("")
}
},
//按照示意图依次调用
beforeCreate(){
console.log("调用了beforeCreate钩子函数");
},
created(){
console.log("调用了created钩子函数");
},
beforeMount(){
console.log('调用了beforeMount钩子函数');
},
mounted(){
console.log('调用了mounted钩子函数');
},
beforeUpdate(){
console.log("调用了beforeUpdate钩子函数")
},
updated(){
console.log("调用了updated钩子函数");
},
beforeDestroy(){
console.log("调用了beforeDestroy钩子函数");
},
destroyed(){
console.log("调用了destroyed钩子函数");
}
})
</script>
</body>
</html>
如图所示:
初始化页面依次调用了:
- 调用了beforeCreate钩子函数
- 调用了created钩子函数
- 调用了beforeMount钩子函数
- 调用了mounted钩子函数
点击更新数据后:
12345
变成了54321
,此时调用了:
- 调用了beforeUpdate钩子函数
- 调用了updated钩子函数
打开F12控制台 直接输入app.$destroy()
主动销毁Vue实例调用:
- 调用了beforeDestroy钩子函数
- 调用了destroyed钩子函数
二、再探究
2.1 beforeCreate之前
初始化钩子函数和生命周期
2.2 beforeCreate和created钩子函数间的生命周期
在beforeCreate和created之间,进行数据观测(data observer) ,也就是在这个时候开始监控data中的数据变化了,同时初始化事件。
2.3 created钩子函数和beforeMount间的生命周期
对于created钩子函数和beforeMount有判断: