【问题标题】:Wanting to loop through array of IDs to fetch data from API [closed]想要遍历 ID 数组以从 API 获取数据 [关闭]
【发布时间】:2020-11-26 19:11:02
【问题描述】:

在这个应用程序中,我从一个 API 获取 ID 并将它们传递到第二个 API 并尝试显示来自第二个 API 的每个 ID 的属性 overviewList.overview.lifeTimeData.energy,但在此示例中,所有我能做的就是显示第一个索引的属性。如何循环遍历 ID 数组并显示每个 ID 的属性?这是我目前所拥有的实时工作版本,代码位于组件 > HelloWorld.vue 下。我知道我需要遍历 ID 数组,但我不知道如何。

https://codesandbox.io/live/68gQlN

【问题讨论】:

    标签: javascript api loops vue.js axios


    【解决方案1】:

    你想做什么不是很清楚。

    但是当你这样做时

          axios.get(
            this.host +
              this.domain +
              `/site/` + ids[0] + `/overview?` +
              this.apiKey,
            this.config
          )
    

    您需要为每个 id 权限运行此查询。 你的方法应该看起来更像这样:

    methods: {
      async getSiteDetails() {
        let ids = [];
        await axios.get(
          this.host +
            this.domain +
              "/sites/list?sortProperty=name&sortOrder=ASC&" +
            this.apiKey,
          this.config
        )
        .then((...responses) => {
          this.siteList = responses[0].data;
          ids = this.siteIdList.concat(responses[0].data.sites.site).map(x => x.id);
        })
        
        ids.forEach(this.getOverviewList);
      },
      async getOverviewList(id) {
        axios.get(
          this.host +
            this.domain +
            `/site/` + id + `/overview?` +
            this.apiKey,
          this.config
        )
        .then(((...responses) => {
            this.overviewList[id] = responses[0].data;
        }))
        .catch(errors => {
          console.log(errors);
        });
      },
    }
    

    【讨论】:

    • 效果很好,谢谢!我一直在努力让它发挥作用。
    猜你喜欢
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 2010-12-12
    • 2021-10-02
    • 2012-02-26
    • 1970-01-01
    相关资源
    最近更新 更多