elementui中的table全选时有条件限制怎么处理

107 阅读1分钟

前提

在使用elementui的table多选时,我们会有条件限制,比如不满足某个条件时不可选择,这时使用selectable属性可以解决

handleSelectable(row, index) {
  if (!row.canChoose) {
    return false
  }
  return true
}

但是在选择标头的全选时,看起来某一些不符合条件的数据的多选框被置灰了,但是所有的数据都被选择了

image.png

解决

网上的一些文章大多数有两种解决方法

  1. 禁止全选(对于我来说肯定是不行的)
  2. 重写checkbox列(对于我来说有点费时间,需要重写单选/部分选择/全选/以及单选和全选的关系等)

我的解决办法

  1. 既然都被选了,那我把不需要的直接反选不就好了(嘻嘻),一查文档,确实有这个反选的方法

image.png

1. 首先在table上绑定select-all方法监听全选
@select-all="selectAll"

2. 处理selectAll
selectAll(selection) {
    // 大于或等于10的时候表示点击了全选
    if (selection.length >= 10) {
      // 设置选择的数据
      this.chooseSelection = selection.filter((item) => item.canChoose)
      // 获取不需要被保存的数据
      const cantChoose = selection.filter((item) => !item.canChoose)
      if (cantChoose.length) {
        cantChoose.forEach((row) => {
          // 将某一行固定为不选
          this.$refs.multipleTable.toggleRowSelection(row, false)
        })
      }
    }
},