我们称一个new Vue()为一个实例,一个Vue的生命周期包括8个阶段:
下面通过一个实例来对Vue的生命周期进行理解。查看演示界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue的生命周期</title>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="myApp" :style="style">
<p>{{msg}}</p>
<p>Vue 的生命周期分为八个阶段,分别是:
<br><br><br>实例创建之前——>实例创造之后——>编译,挂载之前——>编译,挂载之后——>更新之前——>更新之后——>销毁之前——>销毁之后。</p>
<button @click="updateFun">更新组件</button>
<button @click="destroyFun">销毁组件</button><br>
<img src="https://cn.vuejs.org/images/lifecycle.png">
</div>
<script>
var vm = new Vue({
el: "#myApp",
data: {
style: "textAlign:center;marginTop:50px;",
msg: "Welcome to Vue World"
},
methods: {
// 更新组件
updateFun(){
this.msg = 'Hello Vue!';
},
// 销毁组件
destroyFun(){
vm.$destroy();
}
},
beforeCreate(){
alert("组件实例刚刚创建,还未进行数据观测和事件配置!");
},
//这是我们比较常用的。一般用来初始化数据。
created(){
alert("实例刚刚创建完成,已经进行数据观测和事件配置");
},
beforeMount(){
alert("编译之前,还没挂载。");
},
//这个我们也比较常用的。
mounted(){
alert("模板编译之后,已经挂载,此时才会渲染页面,才能看到页面上的数据展示");
},
beforeUpdate(){
alert("组件更新之前");
},
updated(){
alert("组件更新之后,更新完之后数据才会发生变化。");
},
beforeDestroy(){
alert("销毁实例之前。");
},
destroyed(){
alert("组件销毁之后");
}
});
</script>
</body>
</html>
京公网安备 11010502036488号