【发布时间】:2020-05-13 20:02:13
【问题描述】:
不确定何时使用计算属性和 watch 来显示我的数据。我正在使用 PokeAPI 构建一个应用程序,并且我想在 Type 和 Generation 之间切换以显示 pokemon。到目前为止,我有一个 JS 文件,将所有口袋妖怪存储在一个数组中:
//pokeData.js
import axios from 'axios'
const allPokes = [];
export default{
getPokemon(){
if(allPokes.length === 0){
for(let i=1; i<=809; i++){
axios.get(`https://pokeapi.co/api/v2/pokemon/${i}`)
.then(response => {
allPokes.push(response.data);
allPokes.sort((a, b) => a.id - b.id);
});
}
}
return allPokes
}
}
我不想从 API 重复调用 809 对象,所以我在我的 Vue 中的 mount() 中调用它们,并希望从那里过滤它们:
//Container.vue
//takes two props, 'currentType' and 'currentGen', to use to filter the pokemon
<template>
<div
v-for="(pokemon, index) in allPokemon"
:key="index">
<h2>{{ pokemon.name }}</h2>
</div>
</template>
<script>
import Pokemon from '../pokeData'
export default {
props: ['currentType', 'currentGen'],
data(){
return{
allPokemon: [],
}
},
mounted(){
this.allPokemon = Pokemon.getPokemon();
},
watch: {
currentType: function(newType){
const typePokes = this.allPokemon.filter(pokemon => {
if(pokemon.types[0].type.name == newType){
return true
}
this.allPokemon = typePokes
});
我知道这是错误的,但我不知道如何解决它。我知道您可以按照官方文档中的建议使用列表渲染,但没有说明如何将其用于多个过滤器。 https://vuejs.org/v2/guide/list.html#Replacing-an-Array
欢迎任何建议:如何更好地缓存初始 API 调用;使用手表或计算...
【问题讨论】:
标签: javascript vue.js