javascript - 我将如何遍历 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>
解决方案
看起来“.../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>
推荐阅读
- java - 如何在java中找到实现接口的所有子类?
- mule - 我可以在不重启 Mule 的情况下重启 ActiveMQ 吗?
- excel - Trim 函数和 WorksheetFunction.Trim 不会删除前导或尾随空格
- python - 在破折号中,选择单个单选按钮时,如何使用回调更新图形?
- python - 线性回归模型(使用梯度下降)不收敛于波士顿住房数据集
- reverse-proxy - Firebase 托管是否需要反向代理?
- c - 如何像 Linux 命令 ls 一样格式化输出以打印
- html - 如何在横幅上显示文本叠加图像
- r - 在不知道变量名称的情况下将数据框重塑为三列宽
- php - 创建一个目录,将另一个目录的文件复制到其中,然后在 phpMyAdmin 中创建一个表?