背景
我们在使用 element ui
的 Table
组件构建带复选框的表格时,我们希望根据条件禁用或者隐藏某行选择框。如下图所示:
解析
通过查看 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> 项
<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>
版权属于:瞭月
本文链接:https://www.lervor.com/archives/180/
版权声明:本文为瞭月原创文章,转载请附上原文出处链接和本声明。