vue 常见的生命周期有如下 6 个:
beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
beforeCreate
是在 var vm = new Vue(...)
之前运行的。
此时 el ,data 等属性还是 undefined。
created
此时 data 已经被初始化,但是还是没有与 html 中的元素进行关联。
this.$el 为 undefined。
beforeMount
this.$el 为 关联的 dom 元素。
updated
不要在 updated 里面更新数据,会死循环的。
图证
image.pngvar vm = new Vue({
el : "#showTraceResult",
data : {
traceResult : ["11","22"
],
},
beforeCreate: function(){
console.log("取回数据");
console.log(this.traceResult);
$.ajaxSettings.async = false; // 设置 $.get 同步执行
$.get("/api/trace",function(data){
console.log(data);
//this.traceResult = ["111","222"];
//console.log(this.traceResult)
});
$.ajaxSettings.async = true;
},
/* 在实例创建完成后被立即调用。
在这一步,实例已完成以下的配置:数据观测 (data observer),属性和方法的运算,watch/event 事件回调。
然而,挂载阶段还没开始,$el 属性目前不可见。 */
created :function(){
console.log('created');
console.log(this.traceResult)
this.traceResult = ["111","222"];
console.log(this.traceResult)
console.log(this.$el);
},
//在挂载开始之前被调用:相关的渲染函数首次被调用
beforeMount : function(){
console.log('beforeMount');
console.log(this.traceResult)
this.traceResult = ["1111","2222"];
console.log(this.traceResult);
console.log(this.$el);
},
//el 被新创建的 vm.$el 替换,挂载成功
mounted : function(){
console.log('mounted');
console.log(this.traceResult)
this.traceResult = ["11111","22222"];
console.log(this.traceResult);
console.log(this.$el);
},
//数据更新时调用
beforeUpdate : function(){
console.log('beforeUpdate');
console.log(this.traceResult)
this.traceResult = ["111111","222222"];
console.log(this.traceResult);
console.log(this.$el);
}
});
网友评论