data () {
return {
name: '', // 名称
price: ' ', // 价格
list: [
{ id: 100, name: '外套', price: 199, time: new Date('2010-08-12') },
{ id: 101, name: '裤子', price: 34, time: new Date('2013-09-01') },
{ id: 102, name: '鞋', price: 25.4, time: new Date('2018-11-22') },
{ id: 103, name: '头发', price: 19900, time: new Date('2020-12-12') }
]
}
},
methods: {
addAsset () {
if (this.name === '' || this.price === '') { return alert('请输入完整') }
const asset = {
id: this.list.at(-1).id + 1,
name: this.name,
price: this.price,
time: new Date()
}
this.list.push(asset)
// 清空
this.name = ''
this.price = ''
}
}
实现的效果 点击按钮的时候删除对应行 新增的时候id是用this.list.at(-1)+1来写的 但是删除到0的时候就没有-1项了 所以报undefined
修改的方法 对id做一个判断
更优雅的写法 用?.
const asset = {
id: this.list.at(-1)?.id + 1 || 1,
name: this.name,
price: this.price,
time: new Date()
}
this.list.push(asset)
// 清空
this.name = ''
this.price = ''