vue 操作List

对list的删除操作

var vm = new vue({
el: '#app'
data: {
id: ' ',
name: ' ',
list: [
{ id : 1, name : '奔驰', ctime: new Date() },
{ id : 2, name : '宝马', ctime: new Date() }
]
},
methods: {
delete(id) { //根据传入的ID来删除数据
// 1.根据ID来找到要删除的这一项的索引
// 2. 找到索引后,调用数组的splice方法
// 方法一
this.list.some((item, i) => {
if (item.id == id ){
this.list.splice(i,1)
// 在数组的some方法中,如果return true,就会立即终止这个数组的后续循环,所以相比较foreach,如果想要终止循环,那么建议使用some
return true;
}
})
// 方法二
var index = this.list.findIndex(item => {
if ( item.id == id) {
return true;
}
})
this.list.splice(index,1)
}
// 方法三(不推荐,因为无法被终止)
this.list.forEach(item => {
if (item.id == id){
this.list.splice(i,1)
}
})
}
})

var car = { id : this.id, name: this.name} this.list.push(car)

参考: https://blog.csdn.net/qq_41967899/article/details/90259875

猜你喜欢

转载自www.cnblogs.com/xguai/p/11815736.html