【发布时间】: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