我在VueJs,简单任务列表,已完成和未完成的代码中都有此代码,当我选中或取消选中该框时,任务应移至正确的列表。
var app = new Vue({
el: '#vueapp',
data: {
tasks: [{
id: 1,
description: 'Do some Stuff',
completed: false
},
{
id: 2,
description: 'Go to pharmacy',
completed: false
},
{
id: 3,
description: 'Go to doctor',
completed: true
},
{
id: 4,
description: 'Do some Slask',
completed: false
},
]
},
methods: {
toggleTask(key) {
this.tasks[key].completed = !this.tasks[key].completed;
}
},
computed: {
incompleteTasks() {
return this.tasks.filter(task => !task.completed);
},
completedTasks() {
return this.tasks.filter(task => task.completed);
},
}
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="vueapp">
<h2>Completed Tasks</h2>
<ul>
<li v-for="(task, key) in completedTasks">{{ task.description }}<input type="checkbox" v-model="task.completed"></li>
</ul>
<h2>Incomplete Tasks</h2>
<ul>
<li v-for="(task, key) in incompleteTasks">{{ task.description }}<input type="checkbox" v-model="task.completed"></li>
</ul>
</div>
在Chrome中进行了测试。尝试检查第一个未完成的任务,它会成功移到上一个列表中,但是下一个未完成的任务也会被检查。!!!!
答案 0 :(得分:2)
您需要在循环:key="task.id"
中添加key。
要给Vue一个提示,使其可以跟踪每个节点的身份,从而重用和重新排列现有元素,您需要为每个项目提供唯一的key属性。键的理想值是每个项目的唯一ID。
var app = new Vue({
el: '#vueapp',
data: {
tasks: [{
id: 1,
description: 'Do some Stuff',
completed: false
},
{
id: 2,
description: 'Go to pharmacy',
completed: false
},
{
id: 3,
description: 'Go to doctor',
completed: true
},
{
id: 4,
description: 'Do some Slask',
completed: false
},
]
},
methods: {
toggleTask(key) {
this.tasks[key].completed = !this.tasks[key].completed;
}
},
computed: {
incompleteTasks() {
return this.tasks.filter(task => !task.completed);
},
completedTasks() {
return this.tasks.filter(task => task.completed);
},
}
});
.as-console-wrapper { display: none !important; }
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="vueapp">
<h2>Completed Tasks</h2>
<ul>
<li v-for="(task, key) in completedTasks" :key="task.id">{{ task.description }}<input type="checkbox" v-model="task.completed"></li>
</ul>
<h2>Incomplete Tasks</h2>
<ul>
<li v-for="(task, key) in incompleteTasks" :key="task.id">{{ task.description }}<input type="checkbox" v-model="task.completed"></li>
</ul>
</div>