likes
comments
collection
share

【紧贴业务,拿来即用】表格行勾选各种需求通通解决

作者站长头像
站长
· 阅读数 13

需求

  • 经常会遇到表格行勾选的场景,产品会说

    • 要支持表单搜索
    • 要支持表头搜索
    • 哎呀,数据量太大,后端分页
    • 哎呀,后端太忙,数据量不大,前端分页把
    • 我上面全都要,而且用户勾了表格1,筛选后没了,再点确定也要传给后端绑定成功
  • 其实就是用户勾了,只要用户不主动取消,怎么操作最后都要生效!!!

分析

【紧贴业务,拿来即用】表格行勾选各种需求通通解决

  • 其实只需要知道用户每次点击行 checkbox 的意图,将对应的选中数据 tableSelectList 维护好即可(这个是用户触发,也可基于业务进行代码触发)
  • 不管支持用户什么操作,只要导致表格当前展示数据变化,并且其中含有 tableSelectList 中数据就会自动勾选;保存时直接把 tableSelectList 扔给后端就满足需求
  • 重点就是维护 tableSelectList,主要四个情况
    • 单个勾选
    • 单个取消
    • 当页勾选
    • 当页取消

实现

  • 通过监听 select(勾选行 Checkbox )、select-all(勾选全选 Checkbox )事件,进行处理四种情况
// this.rowKey:表格行唯一 id 标识

// 单个勾选、取消
select(selection, row) {
  const isAdd = selection.some((selectRow) => selectRow[this.rowKey] === row[this.rowKey])
  this.rowChangeAll(row, isAdd)
},
// 当页勾选、取消
selectAll(selection) {
  // 默认当页全选
  let isAdd = true
  let changeSelect = selection.slice()
  if (!changeSelect.length) {
    // 取消当页全选,获取表格当前页所有数据
    isAdd = false
    changeSelect = this.tableData.slice()
  }
  // 全选时,存在之前已经选上;只加不删
  changeSelect.forEach((row) => {
    this.rowChangeAll(row, isAdd)
  })
},
// row:表格行;isAdd:是否勾选
rowChangeAll(row, isAdd) {
  const index = this.tableSelectList.findIndex((item) => item[this.rowKey] === row[this.rowKey])
  // 不存在只能加,存在只能减
  if (index === -1) {
    if (isAdd) {
      this.tableSelectList.push(row)
    }
  } else {
    if (!isAdd) {
      this.tableSelectList.splice(index, 1)
    }
  }
},
  • 监听表格当前展示数据变化,触发此方法进行比对选中
rowSelect() {
  this.$nextTick(() => {
    this.tableSelectList.forEach((select) => {
      const resRow = this.tableData.find((row) => select[this.rowKey] == row[this.rowKey])
      if (resRow) {
        this.$refs.elTable.toggleRowSelection(resRow, true)
      }
    })
  })
},

体验

希望看完的朋友可以点个喜欢/关注,您的支持是对我最大的鼓励