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)
			}
		})
	}	
})

对list的新增操作

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

你可能感兴趣的:(Vue)