我的问题很简单,我想在运行时分配数据并在vue实例中再次获取它们 data() { return { panels:[], }; }, created() { this.fetchPanels(); //console.log(this) , i can find panels already assigned in this instance //console.log(this.panels) , it gives me zero array }, methods: { fetchPanels() { this.$http .get(Shared.siteUrl+"/api/" + this.category_title + "/panels") .then(function(response) { this.panels = response.body.data; }); },
3 回答

一只甜甜圈
TA贡献1836条经验 获得超5个赞
如果您打算使用async / await(我同意,您应该使用),那么您也应该在http调用中使用它。await somefunc().then()感觉就像是风格的混合。这具有缩短的优点。
data() {
return {
panels:[],
};
},
async created() {
await this.fetchPanels();
console.log(this.panels);
},
methods: {
async fetchPanels() {
const response = await this.$http.get(Shared.siteUrl + "/api/" + this.category_title + "/panels")
this.panels = response.body.data;
},
请记住,Vue生命周期不会等待您的异步生命周期挂钩。在此示例中,这将不是问题,但牢记绝对是一件好事。即,如果您添加了
mounted() {
console.log(this.panels);
},
它会变成空的,因为其中的异步任务created()现在将在mounted()
添加回答
举报
0/150
提交
取消