Vue 实例有一个完整的生命周期,也就是从开始创建、初始化数据、编译模板、挂载Dom→渲染、更新→渲染、卸载等一系列
过程,我们称这是 Vue 的生命周期。通俗说就是 Vue 实例从创建到销毁的过程,就是生命周期。
过程,我们称这是 Vue 的生命周期。通俗说就是 Vue 实例从创建到销毁的过程,就是生命周期。
生命周期钩子:
beforecreate : 可以在这加个loading事件,在加载实例时触发 ,可以在这加个loading事件
created
: 初始化完成时的事件写在这里,
如在这结束loading事件
,异步请求也适宜在这里调用
mounted
: 挂载元素,获取到DOM节点
updated
: 如果对数据统一处理,在这里写上相应函数
beforeDestory: destoryed: 可以做一个确认停止事件的确认框,当前组件已被删除,清空相关内容
nextTick
: 更新数据后立即操作dom
生命周期的执行过程:
上面的图是vue1.0 和
vue2.0生命周期钩子的对比,应该可以看的很明白了。。。
要用就只需要把代码写入就可以了比如:
beforeCreate: function () {
console.log("创建前状态")
console.log("%c%s", "color:red" , "el : " + this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
},
created: function () {
console.log("创建完毕状态");
console.log("%c%s", "color:red","el : " + this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
},
beforeMount: function () {
console.log("挂载前状态");
console.log("%c%s", "color:red","el : " + (this.$el));
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
},
mounted: function () {
console.log("挂载结束状态");
console.log("%c%s", "color:red","el : " + this.$el);
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
},
beforeUpdate: function () {
console.log("更新前状态");
console.log("%c%s", "color:red","el : " + this.$el);
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
},
updated: function () {
console.log("更新完成状态");
console.log("%c%s", "color:red","el : " + this.$el);
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
},
beforeDestroy: function () {
console.log("销毁前状态");
console.log("%c%s", "color:red","el : " + this.$el);
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
},
destroyed: function () {
console.log("销毁完成状态")
console.log("%c%s", "color:red","el : " + this.$el);
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data);
},
以上代码放在组件中即可使用;