【问题标题】:Vue data ArraysVue 数据数组
【发布时间】:2021-05-05 16:04:19
【问题描述】:

当我创建一个数组并将数据推入其中时。它变成了一个代理,我不能再对它们使用 JS 数组函数了。

export default {
  name: 'Home',
  components: { PokeList, FilterType, SearchPokemon},
  data() {
        return {
            pokemons: [],
            numOfPokemon: 151,
            types: []
        }
    },
    methods: {
        async prepairPokeIds() {
            for (let i = 1; i <= this.numOfPokemon; i++){
                
                await this.fetchPokemonData(i)
            }
        },
        async fetchPokemonData(id) {      
        try {
            const res = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`)
            const data = await res.json()
            this.types.push(data.types[0].type.name)
            this.pokemons.push(data)
            return data
        } catch (error) {
            console.log(error)
        }
        },
        async test(){
          console.log(this.types.length)
        }
    },
  async created() {
      this.prepairPokeIds()
      await this.test()
      console.log(this.pokemons)
      console.log(this.types)
  }
}
</script>

即使代理目标中有数据,测试函数中的 console.log 也会返回 0 值?

【问题讨论】:

    标签: javascript arrays vue.js


    【解决方案1】:

    在下面的代码中:

    async created() {
      this.prepairPokeIds() // sends a request and executes line below
      await this.test()
      console.log(this.pokemons)
      console.log(this.types)
    }
    

    this.prepairPokeIds() 将触发循环中的第一个请求,控制权返回到created 并执行await this.test() 它立即执行console.log(this.types.length),所以你得到0,这是当时的值。


    下面的代码应该记录正确的值,因为它在第一个请求解决后执行。

    async prepairPokeIds() {
       for (let i = 1; i <= this.numOfPokemon; i++){      
         await this.fetchPokemonData(i)
         console.log(this.types.length)
       }
    },
    

    或者你可以从prepairPokeIds()返回一个promise并在执行this.test()之前等待它

    【讨论】:

      猜你喜欢
      • 2020-07-27
      • 2019-04-20
      • 2021-01-14
      • 1970-01-01
      • 2019-11-13
      • 2018-08-03
      • 2017-10-17
      • 2019-05-02
      • 2017-10-29
      相关资源
      最近更新 更多