我已经为学校嵌套了数据。 生命周期看起来像fetchSchools() - > fetchfetchSchoolData(schoolId) 在渲染学校之前获取嵌套数据的最佳解决方案是什么
var app = new Vue({
el: '#app',
data: {
schools : []
},
created:function{
this.fetchSchools();
//next
this.schools = this.schools.filter(function (school) {
school.additionalData = this.fetchSchoolData(school);
return school;
})
},
methods: {
fetchSchools: function () {
var url = this.buildApiUrl('/api/schools');
this.$http.get(url).then(function (response) {
this.schools = response.data;
}).catch(function (error) {
console.log(error);
});
},
fetchSchoolData: function (school) {
var url = this.buildApiUrl('/api/school-detail?schoolId=' + school.id);
this.$http.get(url).then(function (response) {
return response.data;
}).catch(function (error) {
console.log(error);
});
},
},
})
答案 0 :(得分:0)
您无法从computed property调用异步方法,您可以使用方法或观察程序来运行异步代码。
您可以使用life-cycle hooks之一创建的created或mounted来设置初始数据,从API加载数据等,如下所示:
var app = new Vue({
el: '#app',
data: {
name: '',
schools: [],
fetchSchoolList: true,
schoolsListData: []
},
methods: {
fetchSchoolData: function (schoolId) {
var url = this.buildApiUrl('/api/school-detail?schoolId=' + schoolId);
this.$http.get(url).then(response => {
this.schoolsListData = response.data;
}).catch(function (error) {
console.log(error);
});
},
},
created () {
this.schools = this.schools.filter(function (school) {
if(fetchSchoolList){
this.fetchSchoolData(school.id)
}
}
},
})
如果{@ 3}}解释,如果它们依赖于上次API调用的输出,则必须将API调用彼此嵌套。