系列文章
前言
el-table单选通过点击行, 再加高亮显示, 不清晰, 多选通过第一列的checkbox选中, 比较直观, 但不支持单选模式, 本文提供一个套路化无脑实现利用多选列实现单选功能.
[套路]系列意在提供一个功能基本实现套路的系列文档, 查就完了.
一、实现
1. el-table 配置
使用 element-table, 功能实现需要配置以下属性
- class 用于隐藏表头的全选框 (html引入vue.js的方式可以不需要, vue项目可以使用)
- highlight-current-row 点击行高亮 (非必须)
- @selection-change=“handleSelectionChange” 实现单选第一列checkbox
- @current-change=“handleCurrentChange” 实现点击行选中
第一列, el-table-column
- type=“selection” 多选
- :selectable=“rowSelectable” 行是否可选 (根据业务实现)
<el-table
class="no-multiple-table"
highlight-current-row
ref="table"
@selection-change="handleSelectionChange"
@current-change="handleCurrentChange"
>
<el-table-column
width="55"
type="selection"
:selectable="rowSelectable"
>
<!--其他列与功能实现无关, 省略-->
</el-table>
2. data块实现
data(){
return {
selectedRow: null,
}
}
3. method块实现
handleSelectionChange(val) {
let that = this;
if (val) {
if (val.length > 1) {
that.$refs.table.clearSelection();
that.$refs.table.toggleRowSelection(val.pop());
}
that.selectedRow = val[0];
} else {
that.$refs.table.clearSelection();
that.selectedRow = null;
}
},
handleCurrentChange(val) {
let that = this;
if (val) {
that.$refs.table.clearSelection();
that.$refs.table.toggleRowSelection(val);
that.selectedRow = val;
} else {
that.$refs.table.clearSelection();
that.selectedRow = null;
}
},
rowSelectable(row, index) {
// 注意: 伪代码, 根据实际业务实现
return row.selectable; // boolean
}
4. style块实现
.el-table__header-wrapper .el-checkbox {
display: none !important;
}