[嗨,我正在使用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>
[看起来像“ ... / 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>
您好,请阅读docs以了解其工作原理。