简体   繁体   中英

splice repeated object from array vue js

I have a Pokemon App that lets you add a pokemon to your 'pokedex'. It takes a pokemon object in this.$store.state.pokemon and pushes it to this.$store.state.pokedex. As a user can push the same object multiple times into the pokedex, I'm having trouble deleting objects from the pokedex using the traditional.splice(index, 1). It currently will delete the last item in the array, not the item it's called on. Is there a way to pass the key of the object to 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)
    }

And the vuex store:

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

If anyone is having a similar problem, I figured out I had to create a new object when pushing the pokemon item to the pokedex array, that I could create a unique reference number for:

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

Then in the component where I rendered the pokemon in state.pokedex, I used the ref as the key:

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

So in the store, I could delete the Object:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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