Loops VueJS:在循环中获取数据以生成完整数据
我为学校设置了嵌套获取数据。 生命周期看起来像fetchSchools()->FetchSchoolData(schoolId) 在渲染之前获取嵌套数据的最佳解决方案是什么Loops VueJS:在循环中获取数据以生成完整数据,loops,render,vue.js,Loops,Render,Vue.js,我为学校设置了嵌套获取数据。 生命周期看起来像fetchSchools()->FetchSchoolData(schoolId) 在渲染之前获取嵌套数据的最佳解决方案是什么 var app = new Vue({ el: '#app', data: { schools : [] }, created:function{ this.fetchSchools(); //next this.schools = t
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);
});
},
},
})
不能从调用异步方法,可以使用方法或观察程序运行异步代码 您可以使用创建的或用于设置初始数据、从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)
}
}
},
})
如前所述,如果API调用依赖于最后一个API调用的输出,则必须相互嵌套API调用。但对于此。fetchSchoolData()我应该知道可以通过fetchSchools()user3816475获取的schoolId。您从哪里获取
schoolId
,关键是您不能从computed调用异步方法。是的,但用许多异步查询准备数据的方法是什么。对于ex.fetchSchools()->FetchSchoolData(schoolId)->fetchSchoolDataPupuls(schoolDataId)和最后的渲染数据。@user3816475您必须将它们一个嵌套在另一个里面,请参见我的类似回答:谢谢您的回答,但在这种情况下,逻辑并不清楚,因为如果我只需要学校,我将得到嵌套的额外数据,如学校数据等。