如何在Nuxt中加载给定urc属性的渲染图片?

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

我是新来的Nuxt(也是Vuejs),我用的是SPA模式,在加载图片时遇到了一个问题。enter image description here我的代码如下。

<template>
<input 
    class="search" 
    type="text" 
    placeholder="search name" 
    v-model="searchTerm" 
    @keyup.enter="filterPokemonList">
<button @click="clearSearchTerm">clear</button>
<div class="container">
    <div class="card" v-for="(pokemon, index) in pokemonList" :key="index" >{{pokemon.name}}
      <!-- Here begins my problem of image loading -->
      <div v-if="pokemon&&pokemon.sprites">
         <img :src="pokemon.sprites.front_default" alt="sprite" width="96px" height="96px">
      </div>
      <div v-if="!pokemon.sprites">
         <img src="~/assets/images/loading.png" alt="loading" width="96px" height="60px">
      </div>
      <!-- End -->
      <nuxt-link :to="'/'+pokemon.name">
        <b-button class="card-btn" size="sm" variant="outline-dark">detail</b-button>
      </nuxt-link>
      <b-button class="card-btn" size="sm" variant="outline-dark" @click="addToEquipe(pokemon)">add</b-button>
    </div>
</div>
</template>

我的页面脚本。

<script>
import axios from 'axios'

const PATH_BASE = 'https://pokeapi.co/api/v2/'
const POKEMON = 'pokemon'
const LIMIT = 'limit='


const getPokemonData$ = url => {
  return axios.get(url)
}
export const getPokemon$ = (name) =>
  axios.get(`${PATH_BASE+POKEMON}/${name}`).then(res => res.data)

export const getPokemons$ = (listNumber) => 
  axios.get(`${PATH_BASE+POKEMON}?${LIMIT+listNumber}`).then(
    res => {
      let pkList = res.data.results
      pkList.map((pk) =>
        getPokemonData$(pk.url).then(res =>
          pk.sprites = res.data.sprites
        )
      )
      return pkList
    } 
  )
export default {
data() {
    return {
      entirePokemonsCache: [],
      pokemonList: [],
      searchTerm: "",
    }
},
async asyncData (context) {
    const result = await getPokemons$(100)
    return { pokemonList: result }
},
</script>

正如你所看到的,当我用HTTP GET得到数据时,在数据里面,对于哪个数据,我又做了一个相关的HTTP GET(url在数据里面),使每个数据都得到另一个属性。

javascript vue.js nuxt.js
1个回答
0
投票

我选择了另一个解决方案,得到 https://pokeapi.co/api/v2/pokemon/id 一个一个地找,而不是一个一个地找。https://pokeapi.co/api/v2/pokemon 并做一个循环(mapfor)

axios.get('https://pokeapi.co/api/v2/**pokemon**').then(
    res => {
        let pkList = res.data.results
        pkList.map((pk) =>
            axios.get(pk.url).then(res =>
            pk.sprites = res.data.sprites
            ....

或者如果你有其他的解决方案,请告诉我:)

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