繁体   English   中英

从数组vue js拼接重复的object

[英]splice repeated object from array vue js

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

//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);
    }

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

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>

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM