更改表格多选为单选
问题描述: 项目开发过程中遇到将多选表格修改为单选的需求。实现了其功能便来记录一下。
解决方案:
- 将表头多选框全选功能关闭
- 将列表中的多选改为单选
实施代码:
<template>
<el-table
ref="multipleTable"
:data="tableData"
tooltip-effect="dark"
:header-cell-class-name="cellClass"
style="width: 100%"
@select="handleSelect"
@selection-change="handleSelectionChange">
<el-table-column
type="selection"
width="55">
</el-table-column>
<el-table-column
label="日期"
width="120">
<template slot-scope="scope">{{ scope.row.date }}</template>
</el-table-column>
<el-table-column
prop="name"
label="姓名"
width="120">
</el-table-column>
<el-table-column
prop="address"
label="地址"
show-overflow-tooltip>
</el-table-column>
</el-table>
<div style="margin-top: 20px">
<el-button @click="toggleSelection()">取消选择</el-button>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [{
date: '2016-05-03',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
}, {
date: '2016-05-02',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
}, {
date: '2016-05-04',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
}],
multipleSelection: [],
currentRow:{}
}
},
methods: {
// 禁用表格头部多选按钮
cellClass(row){
if(row.columnIndex === 0){
return 'disabledCheck'
}
},
//多选改造单选
handleSelect(selection, row) {
if (selection.length > 1) {
this.$refs.multipleTable.clearSelection();
this.$refs.multipleTable.toggleRowSelection(selection.pop());
} else {
this.multipleSelection = selection;
}
this.setCurrentRow(row);
},
// 点击操作一栏设置当前操作行数据
setCurrentRow(row) {
this.currentRow = row;
},
toggleSelection(rows) {
if (rows) {
rows.forEach(row => {
this.$refs.multipleTable.toggleRowSelection(row);
});
} else {
this.$refs.multipleTable.clearSelection();
}
},
handleSelectionChange(val) {
this.multipleSelection = val;
}
}
}
</script>
<style>
//关闭表头全选按钮
.el-table /deep/.disabledCheck > .cell .el-checkbox__inner{
display: none !important;
position: relative;
}
.el-table /deep/.disabledCheck > .cell::before{
display: block;
content:"";
position: absolute;
text-align: center;
width: 100%;
}
</style>