Vue生命周期图示
八个阶段:
阶段 | 描述 |
---|---|
beforeCreate | 创建前,可在这增加loading事件 |
created | 创建完毕后,可在这结束loading,做一些初始化,实现函数自执行 |
beforeMount | 挂载前 |
mounted | 挂载结束后 |
beforeUpdate | 更新前 |
updated | 更新完成 |
beforeDestroy | 实例销毁之前调用。在这一步,实例仍然完全可用。 |
destroyed | Vue 实例销毁后调用。调用后,Vue 实例指示的所有东西都会解绑定,所有的事件监听器会被移除,所有的子实例也会被销毁。 该钩子在服务器端渲染期间不被调用。 |
实例演示
<div id="app">
<p>{{ msg }}</p>
</div>
var app = new Vue({
el: '#app',
data: {
msg : "hello world"
},
beforeCreate: function () {
console.group('beforeCreate');
console.log("%c%s", "color:red" , "el : " + this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
console.log("%c%s", "color:red","message: " + this.msg)
},
created: function () {
console.group('created');
console.log("%c%s", "color:red","el : " + this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
console.log("%c%s", "color:red","message: " + this.msg);
},
beforeMount: function () {
console.group('beforeMount');
console.log("%c%s", "color:red","el : " + (this.$el));
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
console.log("%c%s", "color:red","message: " + this.msg);
},
mounted: function () {
console.group('mounted');
console.log("%c%s", "color:red","el : " + this.$el);
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
console.log("%c%s", "color:red","message: " + this.msg);
},
beforeUpdate: function () {
console.group('beforeUpdate');
console.log("%c%s", "color:red","el : " + this.$el);
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
console.log("%c%s", "color:red","message: " + this.msg);
},
updated: function () {
console.group('updated');
console.log("%c%s", "color:red","el : " + this.$el);
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
console.log("%c%s", "color:red","message: " + this.msg);
},
beforeDestroy: function () {
console.group('beforeDestroy');
console.log("%c%s", "color:red","el : " + this.$el);
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
console.log("%c%s", "color:red","message: " + this.msg);
},
destroyed: function () {
console.group('destroyed');
console.log("%c%s", "color:red","el : " + this.$el);
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
console.log("%c%s", "color:red","message: " + this.msg)
}
})
复制上面代码编译后分析:
beforecreated阶段, el 和 data 并未初始化 ;
created阶段 ,data 数据已初始化,el未完成初始化;
beforeMount阶段, el 和 data均已初始化,可以看到此时el还是 {{msg}},这里就是应用的 Virtual DOM(虚拟Dom)技术,先把坑占住了,到后面mounted挂载的时候再把值渲染进去;
mounted :完成挂载,el值已经渲染出来了;
控制台继续updata操作:
可以看出来,data数据变化后进行了updata操作
app.msg = "sweet cat"
控制台继续destroy 操作:
app.$destroy();