Vue一共有10个生命周期函数,我们可以利用这些函数在Vue的每个阶段都进行操作数据或者改变内容。
直接上官网的一张图
有两个函数在以后组件的内容讲解。
10个生命周期函数:
beforeCreate:function(){
console.log('1-beforeCreate 初始化之后');
},
created:function(){
console.log('2-created 创建完成');
},
beforeMount:function(){
console.log('3-beforeMount 挂载之前');
},
mounted:function(){
console.log('4-mounted 被创建');
},
beforeUpdate:function(){
console.log('5-beforeUpdate 数据更新前');
},
updated:function(){
console.log('6-updated 被更新后');
},
activated:function(){
console.log('7-activated');
},
deactivated:function(){
console.log('8-deactivated');
},
beforeDestroy:function(){
console.log('9-beforeDestroy 销毁之前');
},
destroyed:function(){
console.log('10-destroyed 销毁之后')
}
生命周期的展示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>生命周期</title>
<script type="text/javascript" src="https://unpkg.com/vue@2.5.16/dist/vue.js" ></script>
</head>
<body>
<h1>生命周期</h1>
<hr>
<div id="app">
{{ count }}
<p><button @click="add">add</button></p>
</div>
<button onclick="app.$destroy()">销毁</button>
<script>
var app = new Vue({
el : '#app',
data : {
count : 1
},
methods : {
add : function(){
this.count++;
}
},
beforeCreate:function(){
console.log('1-beforeCreate 初始化之前');
},
created:function(){
console.log('2-created 创建完成');、
//在项目中比较常用的是在这里进行创建动画,然后在第四步销毁动画,恢复正常页面。
//例如正常页面加载时候出现的那个loging
},
beforeMount:function(){
console.log('3-beforeMount 挂载之前');
},
mounted:function(){
console.log('4-mounted 被创建');
},
beforeUpdate:function(){
console.log('5-beforeUpdate 数据更新前');
},
updated:function(){
console.log('6-updated 被更新后');
},
//78在控制台不输出,他俩是有特殊用途的,在路由和组件时会用到
activated:function(){
console.log('7-activated');
},
deactivated:function(){
console.log('8-deactivated');
},
beforeDestroy:function(){
console.log('9-beforeDestroy 销毁之前');
},
destroyed:function(){
console.log('10-destroyed 销毁之后')
}
})
</script>
</body>
</html>