vue 表格删除功能结合filter更新对象数组

首先: filter方法的使用可以参考: https://blog.csdn.net/weixin_41615439/article/details/108661807
使用filter操作对象数组,可以减少不必要的请求;如果不是对象数组,那filter方法是没有改变原数组的。
1、首先,表格数据我已经拿到
在这里插入图片描述
2、点击删除,逻辑代码如下:

// 删除表格某个数据
    del(id) {
      // 判断是多选还是单选
      let delType = id instanceof Array
      let length = 0
      let changeId = ''
      if(delType) {
        // 多条
        length = id.length
        // 数组转字符串
        changeId = id.join(',')
      } else {
        changeId = id
      }
      this.$confirm({
        title: delType? `您确定要删除这${length}个站点吗?`: '您确定要删除该站点吗?',
        content: '删除后不可恢复哦',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          // 调用删除接口
          delData(changeId)
            .then(res => {
              if(res.data.code === 0) {
                // 删除成功更新数据
                if(delType) {
                  // 如果是多选,遍历id数组
                  id.forEach(item => {
                    // 通过选中的id与原对象数组的id判断,不相同则留着
                    this.tableData = this.tableData.filter(it => it.id != item)
                  })
                } else {
                  // 单选则直接把选中的id和原对象数组的id比较
                  this.tableData = this.tableData.filter(it => it.id != changeId)
                }
              }
            })
        },
        onCancel() {
          // 关闭提示
        },
      });
    },

3、运行后保错:
在这里插入图片描述
4、修改的代码:

// 删除表格某个数据
    del(id) {
      // 解决报未定义的错
      let that = this
      // 判断是多选还是单选
      let delType = id instanceof Array
      let length = 0
      let changeId = ''
      if(delType) {
        // 多条
        length = id.length
        // 数组转字符串
        changeId = id.join(',')
      } else {
        changeId = id
      }
      that.$confirm({
        title: delType? `您确定要删除这${length}个站点吗?`: '您确定要删除该站点吗?',
        content: '删除后不可恢复哦',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          // 调用删除接口
          delData(changeId)
            .then(res => {
              if(res.data.code === 0) {
                // 删除成功更新数据
                if(delType) {
                  // 如果是多选,遍历id数组
                  id.forEach(item => {
                    // 通过选中的id与原对象数组的id判断,不相同则留着
                    that.tableData = that.tableData.filter(it => it.id != item)
                  })
                } else {
                  // 单选则直接把选中的id和原对象数组的id比较
                  that.tableData = that.tableData.filter(it => it.id != changeId)
                }
              }
            })
        },
        onCancel() {
          // 关闭提示
        },
      });
    },

主要是增加了

let  that = this

只因热爱,愿迎万难

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值