【问题标题】:splice repeated object from array vue js从数组vue js拼接重复的对象
【发布时间】:2020-11-09 19:45:58
【问题描述】:

我有一个口袋妖怪应用程序,可让您将口袋妖怪添加到您的“pokedex”中。它在 this.$store.state.pokemon 中获取一个 pokemon 对象并将其推送到 this.$store.state.pokedex。由于用户可以将同一个对象多次推送到 pokedex 中,因此我无法使用传统的 .splice(index, 1) 从 pokedex 中删除对象。它当前将删除数组中的最后一项,而不是调用它的项。有没有办法把对象的key传给splice?

//Pokedex.vue
<template>
    <pokedex-card 
        v-for="(pokemon, i) in pokedex" 
        :key="`${i}+${pokemon.id}`"
        :pokemon="pokemon">
          <button @click="releasePokemon(i)">Release {{ pokemon.name }} ?</button>
    </pokedex-card>
</tempalte>

methods:{
    releasePokemon(id){
      this.$store.dispatch('releasePokemon', id)
    }

还有 vuex 商店:

//index.js
REMOVE_FROM_POKEDEX(state, id){
      //find pokemon position in array by matching it's object ID
      var pokePosition = state.pokedex.map(pokemon => { return pokemon.id }).indexOf(id)
      state.pokedex.splice(pokePosition, 1);
    }

【问题讨论】:

  • 因为推送到图鉴的对象是相同的,所以它们具有相同的ID。所以使用 pokemon.id 是行不通的,它只是拼接最后一个数组项,因为它立即匹配条件。在这种情况下,这些建议都不起作用
  • 你有没有试过REMOVE_FROM_POKEDEX中的state.pokedex.splice(id, 1),因为这个方法中的id其实是元素的索引,而不是id
  • 是的,它总是删除数组的最后一项而不是那个索引位置的项
  • 没有办法将 ID 而不是索引传递给Array.splice() 方法。如果您想使用 ID - 您首先必须自己找到此 ID 的索引(例如通过Array.findIndex() 方法),然后将index 提供给Array.splice()

标签: javascript vue.js


【解决方案1】:

如果有人遇到类似的问题,我发现在将 pokemon 项目推送到 pokedex 数组时我必须创建一个新对象,我可以创建一个唯一的参考编号:

state.pokedex.push( { ref: pokemon.id + state.pokedex.length, poke: pokemon } );

然后在我在 state.pokedex 中渲染 pokemon 的组件中,我使用 ref 作为键:

<pokedex-card 
        v-for="pokemon in pokedex" 
        :key="pokemon.ref"
        :pokemon="pokemon">
</pokedex-card>

所以在商店里,我可以删除对象:

REMOVE_FROM_POKEDEX(state, id){
   let index = state.pokedex.findIndex(pokemon => pokemon.ref === id);
   state.pokedex.splice(index, 1);
}

【讨论】:

    猜你喜欢
    • 2021-03-03
    • 2018-12-02
    • 2018-12-17
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 2022-11-20
    相关资源
    最近更新 更多