Vue对象生命周期
大约 2 分钟VueVue
先上Vue官网的生命周期图片:
- beforeCreate: 元素DOM和数据都还没有初始化
- created:数据data已经初始化完成,方法也已经可以调用,但是DOM未渲染。
- beforeMount:数据data初始化完成,但还没有发生渲染。
- mounted:data数据初始化完成,已经渲染。
- beforeUpdate:只要是页面数据改变了都会触发,数据更新之前,页面数据还是原来的数据。
- updated:数据更新完毕。
- beforeDestroy:组件销毁之前。
- Destroyed:组件销毁之后。
写了一个小demo,来实际了解一下Vue生命周期,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue生命周期</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id = 'app'>
</div>
<script >
var Test={
template:`
<div>我是Test组件{{ msg }}
<button @click="msg+='1'">msg+1</button>
</div>
`,
data(){
return{
msg:'HELLO VUE'
}
},
//组件创建前
beforeCreate(){
console.log('组件创建前')
console.log(this.msg)
},
//组件创建后
created(){
console.log('组件创建后')
console.log(this.msg)
},
//Dom挂载前
beforeMount(){
console.log('Dom挂载前')
console.log(document.body.innerHTML)
},
//Dom挂载后
mounted(){
console.log('Dom挂载后')
console.log(document.body.innerHTML)
},
//基于数据更新前
beforeUpdate(){
console.log('数据更新前')
console.log(document.body.innerHTML)
},
//基于数据更新后
updated(){
console.log('数据更新后')
console.log(document.body.innerHTML)
},
//销毁前
beforeDestroy(){
console.log('销毁前')
},
//销毁后
destroyed(){
console.log('销毁后')
},
//组件停用
deactivated(){
console.log('组件停用')
},
//组件激活
activated (){
console.log('组件激活')
}
}
new Vue({
el:'#app',
components:{
Test
},
template:`
<div>
<keep-alive><test v-if='testshow'></test></keep-alive></br>
<button @click='clickbut'>销毁组件</button>
</div>
`,
data(){
return {
testshow:true
}
},
methods:{
clickbut(){
this.testshow=!this.testshow
}
}
})
</script>
</body>
</html>
输出结果如下:
由图可知,组件创建前,数据没有初始化,无法获取到数据,组件初始化后,可以获取到数据。
点击msg+1会调用beforeUpdate,updated钩子函数,点击销毁组件会调用组件停用钩子函数。
至此,对Vue生命周期有了一个初步的认识,在以后的学习中再继续深入了解。