我有一个名为任务的组件,其中包含一行与任务相关的表单输入。 tasks
从 GET JSON 请求(现有条目)中检索。
<task v-for="task in tasks" :task="task"></task>
现在,我想要一个按钮来添加一个新的空白输入行,以便他们可以添加新条目。
<button type="button" @click="addTask()">New</button>
我尝试将一个空对象取消转移到任务中:
addTask() {
this.tasks.unshift({});
},
但是,这只是复制了我的任务的最后一行,而不是将新行添加到任务的开头。
将项目添加到现有列表的最佳方式是什么?
最佳答案
在组件上使用 v-for
指令时,您需要指定一个 key
属性,为每个组件提供一个唯一的值。否则,Vue 将尝试重用元素。
来自documentation :
The
key
special attribute is primarily used as a hint for Vue’s virtual DOM algorithm to identify VNodes when diffing the new list of nodes against the old list. Without keys, Vue uses an algorithm that minimizes element movement and tries to patch/reuse elements of the same type in-place as much as possible.
在您的情况下,指定键的最佳方法是将 id
属性与每个 task
关联并将其用作键:
<task v-for="task in tasks" :task="task" :key="task.id"></task>
关于javascript - 在 vue 中添加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43940587/