背景

我们在使用 element uiTable 组件构建带复选框的表格时,我们希望根据条件禁用或者隐藏某行选择框。如下图所示:

解析

通过查看 ElementUI 官方文档 Table-column Attributes 发现可通过 selectable 实现是否禁用复选框,文档内容如下:

参数说明类型可选值默认值
selectable仅对 type=selection 的列有效,类型为 Function,Function 的返回值用来决定这一行的 CheckBox 是否可以勾选Function(row, index)

同样,可以利用 Table Attributes 中的 cell-class-name,对单元格设置 display: none 达到隐藏复选框的目的,文档内容如下:

参数说明类型可选值默认值
cell-class-name单元格的 className 的回调方法,也可以使用字符串为所有单元格设置一个固定的 className。Function({row, column, rowIndex, columnIndex})/String

源码

具体实现方式如下:

HTML:

<template>
  <div class="page-container">
    <div class="table-alert table-alert-info table-alert-with-icon">
      <span class="table-alert-icon">
        <i class="el-alert__icon el-icon-info" />
      </span>
      <span class="table-alert-message">
        已选择 <a style="font-weight: 600">{{ selectUserList.length }}</a> 项&nbsp;&nbsp;
        <a style="margin-left: 24px;" @click="handleClearSelection">清空</a>
      </span>
    </div>
    <el-table
      ref="table"
      row-key="id"
      border
      fit
      :data="list"
      :cell-class-name="cellClassNameFn"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" width="55" :selectable="checkSelectable" />
      <el-table-column type="index" label="序号" align="center" width="50" />
      <el-table-column label="标题" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.status }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

JS:

<script>
export default {
  data() {
    return {
      list: [{
        id: '1',
        title: '活动1',
        status: 0
      }, {
        id: '2',
        title: '活动2',
        status: 1
      }, {
        id: '3',
        title: '活动3',
        status: 0
      }, {
        id: '4',
        title: '活动4',
        status: 0
      }, {
        id: '5',
        title: '活动5',
        status: 2
      }],
      selectUserList: []
    }
  },
  methods: {
    handleSelectionChange(selection) {
      this.selectUserList = selection
    },
    handleClearSelection() {
      this.selectUserList = []
      this.$refs.table.clearSelection()
    },
    checkSelectable(row) {
      return row.status !== 2 // 状态为 2 禁用复选框(返回值为 true 启用,false 禁用)
    },
    cellClassNameFn(row) {
      if (row.columnIndex === 0 && row.row.status === 1) { // 第一列且状态为 1 通过自定义样式隐藏复选框
        return 'table-column-hidden'
      }
    }
  }
}
</script>

CSS:

<style>
.table-column-hidden .el-checkbox__input {
  display: none
}
</style>
如果觉得我的文章对你有用,请点个赞