如何从VUE中的另一个API加载其他JSON数据?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从VUE中的另一个API加载其他JSON数据?相关的知识,希望对你有一定的参考价值。
我正在通过vue / axios使用此Pokeapi设置PokeDex项目。目前,我正在使用此JSON文件加载所有神奇宝贝名称:https://pokeapi.co/api/v2/pokedex/1/
我想加载来自另一个JSON文件的其他口袋妖怪数据。例如:https://pokeapi.co/api/v2/pokemon/bulbasaur/
除当前设置外,如何动态加载此数据?
当前设置:
<template>
<div id="app">
<div class="pokemon" v-for="pokemon in info">
<span >{{ pokemon.entry_number }}</span>
<span >{{ pokemon.pokemon_species.name }}</span>
</div>
</div>
</template>
<script>
export default {
name: '#app',
data () {
return {
info: [],
loading: true,
errored: false,
}
},
methods: {
},
mounted () {
axios.get('https://pokeapi.co/api/v2/pokedex/1/')
.then(response => {
this.info = response.data.pokemon_entries
})
.catch(error => {
console.log(error)
this.errored = true
})
.finally(() => this.loading = false)
}
};
</script>
答案
我花了一些时间调查您的API并实现了您想要的代码。
一旦第一个API调用中的数据填充了info
数组,我便立即使用观察程序来调用第二个API(有关详细信息,请参见https://vuejs.org/v2/guide/computed.html#Watchers)。此外,我将调用分为不同的方法来改进代码:
<template>
<div id="app">
<div class="pokemon" v-for="(pokemon, index) in info" :key="index">
<span>{{ pokemon.entry_number }}</span>
<span>{{ pokemon.pokemon_species.name }}</span>
<span v-if="pokemon.details">-- details: base_experience{{ pokemon.details.base_experience }}</span>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "#app",
data() {
return {
info: [],
loading: true,
errored: false
};
},
watch: {
info(newValue, oldValue) {
if (oldValue.length === 0 && newValue.length > 0) {
this.loadDetails();
}
}
},
methods: {
getInitialData() {
axios
.get("https://pokeapi.co/api/v2/pokedex/1/")
.then(response => {
this.info = response.data.pokemon_entries;
})
.catch(error => {
console.log(error);
this.errored = true;
})
.finally(() => (this.loading = false));
},
loadDetails() {
this.info.forEach((entry, index) => {
const pokemonName = entry.pokemon_species.name;
const secondApiUrl = `https://pokeapi.co/api/v2/pokemon/${pokemonName}/`;
this.getDetailDataByPokemon(secondApiUrl, pokemonName);
});
},
getDetailDataByPokemon(secondApiUrl, pokemonName) {
axios.get(secondApiUrl).then(response => {
this.mapDetailsToInfo(response, pokemonName);
});
},
mapDetailsToInfo(response, pokemonName) {
// here you can map the required infos to your initial info array.
// as an example I mapped the base_experience
const relevantDetail = response.data.base_experience;
this.info = this.info.map(entry => {
const mappedEntry = entry;
if (entry.pokemon_species.name === pokemonName) {
// here you can map any value
mappedEntry.details = { base_experience: relevantDetail };
}
return mappedEntry;
});
}
},
mounted() {
this.getInitialData();
}
};
</script>
以上是关于如何从VUE中的另一个API加载其他JSON数据?的主要内容,如果未能解决你的问题,请参考以下文章
对列进行 api 调用时,如何从同一表的另一列侧加载某些内容?
如何从动态列表中为 Vue 中的 API 响应创建列表渲染 JSON?