我有以下任务列表应用。我正在尝试实现delete
函数。我需要使用splice
从array
中删除该项目,但如何仅定位我点击其按钮的项目?
https://jsfiddle.net/clintongreen/txtrage5/1/
JS
new Vue({
el: '#tasks',
data: {
message: 'Tasks',
completed: null,
newTaskName: '',
tasklist: [
{ description: 'Read', completed: true },
{ description: 'Write', completed: true },
{ description: 'Edit', completed: false },
{ description: 'Publish', completed: false }
]
},
methods: {
completeTask: function(task){
// console.log(this.tasks.description);
task.completed = true;
},
newTask: function(){
this.tasklist.push({description: this.newTaskName, completed: false});
},
removeTask: function(task){
this.tasklist.splice(this.task.index, 1);
}
}
})
HTML
<div class="container" id="tasks">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
{{ message }}
</h3>
</div>
<ul class="list-group">
<li class="list-group-item clearfix" v-for="task in tasklist" >
{{ task.description }}
<!-- <button class="btn btn-primary btn-sm pull-right" v-if="!task.completed" @click="completeTask(task)">Complete</button> -->
<div class="btn-group btn-group-sm pull-right" role="group" v-if="!task.completed">
<button type="button" class="btn btn-primary" @click="completeTask(task)">Complete</button>
<button type="button" class="btn btn-info">Edit</button>
<button type="button" class="btn btn-danger" @click="removeTask(task)">Delete</button>
</div>
<button class="btn btn-default btn-sm completed text-muted pull-right disabled" v-else>Completed</button>
</li>
<li class="list-group-item clearfix">
<input v-model="newTaskName" @keyup.enter="newTask" type="text" class="pull-left">
<button class="btn btn-success btn-sm pull-right" @click="newTask">Add Task</button>
</li>
</ul>
</div>
</div>
答案 0 :(得分:5)
使用v-for
中任务的索引来决定splice()
中的哪个项目:
v-for="(task, index) in tasklist"
您的按钮:
<button type="button" class="btn btn-danger" @click="removeTask(index)">Delete</button>
然后简单地说:
removeTask: function(index) {
this.tasklist.splice(index, 1);
}
答案 1 :(得分:4)
removeTask: function(task){
this.tasklist.splice(this.tasklist.indexOf(task), 1);
}
答案 2 :(得分:0)
对于Vue2,请使用delete
。 See API.
removeTask: function(index){
this.$delete(this.tasklist, index)
}