我如何遍历pokeAPI以获取所有后续的pokemon数据?

问题描述 投票:0回答:2

[嗨,我正在使用Vuejs来获取一些神奇宝贝数据。因此,我想出了如何检索所有宠物小精灵名称及其api URL以获得有关它们的更多信息。问题是我不知道如何获取这些URL并访问每个神奇宝贝的特定数据。我试图增加一个变量并将其连接到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>
javascript api vue.js
2个回答
1
投票

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

组合它们的方法如下:

axios.get("https://pokeapi.co/api/v2/pokemon/").then(response => {
  this.basicInfo = response.results;
  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>
    

0
投票

您好,请阅读docs以了解其工作原理。

© www.soinside.com 2019 - 2024. All rights reserved.