在新的Vue({})中,我使用以下代码通过投票创建两个学生列表。 如何避免remove()方法重复删除一个学生。
以投票数列出:
data: {
students:
[{
'name': 'Jose',
'last_name': 'Aris',
'document': '201700154',
'campus': 1,
'votes': 0,
},
{
'name': 'Manuel',
'last_name': 'Hernadez',
'document': '201700195',
'campus': 2,
'votes': 3,
},],
},
过滤器:
computed:
{
voted: function ()
{
return this.students.filter((student) => {
return student.votes >= 1;
});
},
unvoted: function ()
{
return this.students.filter((student) => {
return student.votes <= 0;
});
},
},
当两个过滤器具有相同的索引元素时会出现问题:
methods:
{
remove (student, index)
{
if (!confirm(`Are you sure want to delete ${student.name} ${student.last_name}?`))
{
return;
}
this.students.splice(index, 1);
},
}
最后,HTML列表:
<div class="col-md-12">
<h4>LIST VOTED</h4>
<ul class="list-group">
<li v-for="(student, index) in voted" class="list-group-item">
{{index}} {{student.name}} {{student.last_name}} / {{student.document}} <vote :student="student" class="pull-right"></vote>
<a href="" class="btn btn-danger" @click.prevent="remove(student, index)">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</a>
</li>
</ul>
</div>
<div class="col-md-12">
<h4>LIST UNVOTED</h4>
<ul class="list-group">
<li v-for="(student, index) in unvoted" class="list-group-item">
{{index}} {{student.name}} {{student.last_name}} / {{student.document}} <vote :student="student" class="pull-right"></vote>
<a href="" class="btn btn-danger" @click.prevent="remove(student, index)">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</a>
</li>
</ul>
</div>
感谢您阅读
答案 0 :(得分:3)
不要传递索引。
remove (student)
{
if (!confirm(`Are you sure want to delete ${student.name} ${student.last_name}?`))
{
return;
}
const index = this.students.findIndex(s => s === student)
this.students.splice(index, 1);
},
在你的模板中。
<a href="" class="btn btn-danger" @click.prevent="remove(student)">
答案 1 :(得分:2)
您应该使用学生列表中的索引,而不是使用已过滤列表中的索引。只需this.students.splice(this.students.indexOf(student), 1)