您的位置:首页 > 产品设计 > UI/UE

Vue生命周期

2018-03-01 14:42 211 查看

Vue生命周期图示





八个阶段:

阶段描述
beforeCreate创建前,可在这增加loading事件
created创建完毕后,可在这结束loading,做一些初始化,实现函数自执行
beforeMount挂载前
mounted挂载结束后
beforeUpdate更新前
updated更新完成
beforeDestroy实例销毁之前调用。在这一步,实例仍然完全可用。
destroyedVue 实例销毁后调用。调用后,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();


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vue