问题
I have an app with panels you can drag around that are all generated from a basic array of names like so:
<template>
<div id="wrapper">
<nametag
v-for="(name, i) in guests"
:key="i"
:name="name" />
</div>
</template>
<script>
import Nametag from "@/components/Nametag.vue";
module.exports = {
name: 'seating',
components: { Nametag },
data () {
return {
guests: ['Vanessa', 'Lillie', 'Olivia']
}
}
};
</script>
Nametag is a component with all the code for dragging it around on the screen. The x and y it is positioned at are part of its data object.
I'm trying to make a method for removing a name from the guest list but I can't just splice it from the array because when I do that all Vue knows is now the array is a different length and some of the values are different. It just ends up removing the last component in the DOM and, if need be, reassigning new names to the remaining existing components which keep their x and y positions. And the component I tried to remove doesn't get removed it just gets a new name passed to it because the array of guests has changed.
Basically, I don't know how to have Vue remove the component I want it to remove.
回答1:
In order for Vue to know which iterable entry relates to each component, you're going to have to provide a better key. The array index is not appropriate if arbitrary elements are added or removed.
Ideally, your entries will have unique properties. You could create something like this...
data () {
return {
guests: ['Vanessa', 'Lillie', 'Olivia'].map((name, id) => ({ id, name }))
}
}
and use
<nametag v-for="guest in guests" :key="guest.id" :name="guest.name"/>
来源:https://stackoverflow.com/questions/56266808/what-is-the-correct-way-to-remove-a-v-for-element-in-vue