在 Vue 中删除 v-for 元素的正确方法是什么? [英] What is the correct way to remove a v-for element in Vue?
问题描述
我有一个带有面板的应用程序,您可以拖动这些面板,这些面板都是由基本的名称数组生成的,如下所示:
<div id="包装器"><名牌v-for="(name, i) 在客人中":key="我":name="姓名"/>
</模板><脚本>从@/components/Nametag.vue"导入名称标签;模块.出口 = {name: '座位',组件:{名称标签},数据 () {返回 {嘉宾:['Vanessa'、'Lillie'、'Olivia']}}};
Nametag 是一个组件,包含在屏幕上拖动它的所有代码.它所在的 x 和 y 是其数据对象的一部分.
我正在尝试创建一种从客人列表中删除姓名的方法,但我不能只是将其从数组中拼接,因为当我这样做时,Vue 只知道现在数组的长度不同,其中一些价值观不同.它最终会移除 DOM 中的最后一个组件,并在需要时为保留其 x 和 y 位置的其余现有组件重新分配新名称.我试图删除的组件并没有被删除,它只是传递了一个新名称,因为来宾数组已更改.
基本上,我不知道如何让 Vue 移除我想要它移除的组件.
为了让 Vue 知道哪个可迭代条目与每个组件相关,您将不得不提供一个更好的键.如果添加或删除任意元素,则数组索引不合适.
理想情况下,您的条目将具有独特的属性.你可以创建这样的东西...
data() {返回 {客人: ['Vanessa', 'Lillie', 'Olivia'].map((name, id) => ({ id, name }))}}
并使用
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.
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"/>
这篇关于在 Vue 中删除 v-for 元素的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!