【问题标题】:VueJS: fetch data in loop to build full dataVueJS:循环获取数据以构建完整数据
【发布时间】:2017-06-08 23:10:57
【问题描述】:

我已经嵌套了为学校提取数据。 生命周期看起来像 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);
            });
        }, 
      },

    })

【问题讨论】:

    标签: loops render vue.js


    【解决方案1】:

    您不能从computed property 调用异步方法,您可以使用方法或观察者来运行异步代码。

    您可以使用life-cycle hooks 之一创建createdmounted 来设置初始数据、从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 调用的输出,则必须将它们相互嵌套,如 here 所述。

    【讨论】:

    • 但是对于 this.fetchSchoolData() 我应该知道我可以通过 fetchSchools() 获得的 schoolId
    • @user3816475 你从哪里得到schoolId ,关键是你不能从计算中调用异步方法。
    • 是的,但是用许多异步查询准备数据的方法是什么。例如。 fetchSchools()->fetchfetchSchoolData(schoolId)->fetchSchoolDataPupuls(schoolDataId) 最后渲染数据。
    • @user3816475 您必须将它们嵌套在另一个内部,请在此处查看我的类似答案:stackoverflow.com/a/41789265/1610034
    • 感谢您的回答,但在这种情况下逻辑不清楚,因为如果我只需要学校,我将获得嵌套的额外数据,如学校数据等。
    猜你喜欢
    • 2020-05-28
    • 2022-11-17
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多