需求场景: 选择表格数据时,需要控制单条数据的操作按钮是否禁用。
效果图:
html代码:
javascript
<div>
<el-table
ref="multipleTable"
:data="tableData"
tooltip-effect="dark"
style="width: 100%"
@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([tableData[1], tableData[2]])"
>切换第二、第三行的选中状态</el-button
> -->
<el-button @click="toggleSelection()">取消选择</el-button>
</div>
</div>
js代码:
javascript
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 弄",
},
{
date: "2016-05-01",
name: "王小虎",
address: "上海市普陀区金沙江路 1518 弄",
},
{
date: "2016-05-08",
name: "王小虎",
address: "上海市普陀区金沙江路 1518 弄",
},
{
date: "2016-05-06",
name: "王小虎",
address: "上海市普陀区金沙江路 1518 弄",
},
{
date: "2016-05-07",
name: "王小虎",
address: "上海市普陀区金沙江路 1518 弄",
},
],
multipleSelection: [], // 多选存储数据
checkedSelection: {}, // 单选存储数据
};
},
mounted() {
document.onclick = () => {
console.log('单选--checkedSelection', this.checkedSelection);
}
},
methods: {
toggleSelection(rows) {
if (rows) {
rows.forEach((row) => {
this.$refs.multipleTable.toggleRowSelection(row);
});
} else {
this.$refs.multipleTable.clearSelection();
}
},
// 设置单选主要代码
handleSelectionChange(val) {
console.log('val--==', val);
// 默认多选
// this.multipleSelection = val;
// 单选
if(val.length == 1){
let item = val[val.length -1];
this.checkedSelection = JSON.parse(JSON.stringify(item));
}
// 单选选中多条时,需要清空所选数据
if(val.length > 1){
this.$refs.multipleTable.clearSelection(); // 清空选项
this.$refs.multipleTable.toggleRowSelection(val.pop()); // 选中最后点击的数据
}
// 取消选中
if(val.length == 0){
this.checkedSelection = {};
}
},
},
};
css代码:
javascript
<style lang="less" scoped>
// 禁用table全选按钮
.table-wrap{
/deep/.el-table__header{
.el-checkbox{
display: none;
}
}
}
</style>