首页 > 解决方案 > 我将如何遍历 pokeAPI 以获取所有后续 pokemon 数据?

问题描述

嗨,我正在使用 Vuejs 来获取一些口袋妖怪数据。所以我想出了如何检索所有口袋妖怪名称及其 api url 以获取有关它们的更多信息。问题是我不知道如何获取这些 URL 并访问每个 pokemon 的特定数据。我试图增加一个变量并将其连接到 URL 以获取他们的数据,但它不起作用。我还尝试从我已经使用的 api 调用访问数据,但这也没有用。

<template>
  <div>
    <h2>{{subtitle}}</h2>
    <div v-for="pokemon in basicInfo" v-bind:key="pokemon.name">
  <span>{{ pokemon.name}}</span>
</div>
<!-- Nothing is produced, and I dont get I an error -->
<div v-for="pokemon2 in advInfo" v-bind:key="pokemon2.index">
  <span>{{pokemon2}}</span>
</div>

<script>
import axios from "axios";

export default {
  data() {
    return {
      subtitle: "First 150 pokemon",
      basicInfo: [],
      advInfo:[],
      i:0
    };
  },
  methods: {
    // trying to increment i 
  getNext: function(){
    this.i=i++;
  }
  },
  mounted() {
    axios
  // this gets a list of the first 20 pokemon. I can get the pokemon's name and their url
  .get("https://pokeapi.co/api/v2/pokemon/")

  .then(response => {
    this.basicInfo = response.data.results;
  });

      // here I'm trying to access more specific data on each pokemon by concatenating a number to the url 
    axios
      .get("https://pokeapi.co/api/v2/pokemon/5")

      .then(response => {
        this.advInfo= response.data.results;

      });

  }
};
</script>

<style scoped>

</style>

标签: javascriptapivue.js

解决方案


看起来“.../api/v2/pokemon/”产生了一个带有结果数组的对象,并且这些结果包含像“.../api/v2/pokemon/(some id)”这样的uri

组合它们的方法如下:

axios.get("https://pokeapi.co/api/v2/pokemon/").then(response => {
  this.basicInfo = response
  let promises = this.basicInfo.map(result => {
    return axios.get(result.url)
  })
  Promise.all(promises).then(response => {
    this.advInfo = response
  })
});

现在advInfo将是一个数组,就像您期望的那样,您可以使用 v-for... 渲染它。

<div v-for="(pokemon2, i) in advInfo" :key="i">
  <pre>{{pokemon2}}</pre>
</div>

推荐阅读