参考代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue的生命周期</title>
</head>
<body>
<div id="app">
<h1 @click="demo">{{str}}</h1>
</div>
</body>
<script src="./js/vue.min.js"></script>
<script>
// 创建 beforeCreate created
// 挂载 beforeMount mounted,挂载指的是只是用标签进行占位,但是并没有展示数据在视图上
// 更新 beforeUpdate updated
// 销毁 beforeDestroy destroyed
new Vue({
el:"#app",
data:{
str:"VUE实例生命周期"
},
methods:{
demo:function(){
this.str = "这是更新后的数据";
}
},
beforeCreate:function(){
// 在这里我们可以判断用户的是否登录,以及那个用户登录了,然后在下面的created中根据用户的不同来展示不同的数据
console.log("beforeCreate 创建前,视图、模型、控制器 三者都未被创建");
console.log(this.$el);//这个表示的是打印视图实例
console.log(this.$data);//打印数据实例
console.log(this.str);//打印数据的值
console.log("*****************************");//分割线
},
created:function(){
console.log("created 创建后,视图未被创建,模型、控制器 被创建");
console.log(this.$el);
console.log(this.$data);
console.log(this.str);
console.log("*****************************");
},
beforeMount:function(){
// 这里的挂载只是使用标签进行占位,但是并没有真正的展示数据
console.log("beforeMount 挂载前,视图未被真正创建,只是进行占位,模型、控制器 被创建");
console.log(this.$el);
console.log(this.$data);
console.log(this.str);
console.log("*****************************");
},
mounted:function(){
console.log("mounted 挂载后,视图此时被真正创建,模型、控制器 被创建");
console.log(this.$el);
console.log(this.$data);
console.log(this.str);
console.log("*****************************");
},
beforeUpdate:function(){
// 这里的话,一般是先改掉data中的数据,然后在展示到视图中去,这个测试我们可以通过在浏览器这里使用断点来测试
console.log("beforeUpdate 更新前,做更新前的准备工作,data模型数据被改变,视图数据未更新");
console.log(this.$el);
console.log(this.$data);
console.log(this.str);
console.log("*****************************");
},
updated:function(){
console.log("updated 更新后,此时。数据、页面更新完成,data及视图数据全部更新");
console.log(this.$el);
console.log(this.$data);
console.log(this.str);
console.log("*****************************");
},
beforeDestroy:function(){
// 销毁前一般是先销毁数据data,后销毁视图
console.log("beforeDestroy 销毁前,做销毁前的准备工作");
},
destroyed:function(){
console.log("destroyed 销毁后,销毁完成");
}
})
// undefined变量声明且没有赋值;
</script>
</html>
浏览器的控制台运行结果: