[Vue warn]: Error in v-on handler: “TypeError: Cannot read properties of undefined (reading ‘id‘)“

 

 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 = ''

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值