在项目中,经常会有表格展示,前端通常用的是el-table表格,该组件提供的选择为多选,但是当需求要求表格只允许单选怎么写呢?下面就将如何把多选改为单选详细告诉你们~
1. 运用el-table
select-all 代表全选数据时的函数
selection-change 代表选中某行数据时的函数
row-click 代表当某一行被点击时的函数
<el-table
:data="chooseList"
ref="multipleTable"
@select-all="onSelectAll"
@selection-change="handleSelectionChange"
@row-click="onSelectOp"
row-key="id"
>
<el-table-column
type="selection"
width="50"
align="left"
fixed="left"
:reserve-selection="true"
/>
<el-table-column type="index" width="50" align="left" label="序号" />
<el-table-column
label="任务名称"
align="left"
key="taskName"
prop="taskName"
min-width="120px"
:show-overflow-tooltip="true"
>
<template slot-scope="scope">
<span>{{ scope.row.taskName ? scope.row.taskName : "暂无" }}</span>
</template>
</el-table-column>
<el-table-column
label="任务时长(天)"
align="left"
key="duration"
prop="duration"
min-width="120px"
:show-overflow-tooltip="true"
>
<template slot-scope="scope">
<span>{{ scope.row.duration ? scope.row.duration : "暂无" }}</span>
</template>
</el-table-column>
<el-table-column
label="开始年"
align="left"
key="beginYear"
prop="beginYear"
min-width="120px"
:show-overflow-tooltip="true"
>
<template slot-scope="scope">
<span>{{
scope.row.beginYear ? scope.row.beginYear : "暂无"
}}</span>
</template>
</el-table-column>
<el-table-column
label="结束年"
align="left"
key="endYear"
prop="endYear"
min-width="120px"
:show-overflow-tooltip="true"
>
<template slot-scope="scope">
<span>{{ scope.row.endYear ? scope.row.endYear : "暂无" }}</span>
</template>
</el-table-column>
</el-table>
2. 所需要的数据结构,接口正常返回的list结构
chooseList: [
{
"createBy": null,
"createTime": "2023-11-16 10:50:26",
"updateBy": null,
"updateTime": null,
"remark": null,
"id": 165,
"taskName": "飞行任务39",
"orderName": "测试",
"duration": 19,
"beginYear": "2019",
"endYear": "2023",
},
{
"createBy": null,
"createTime": "2023-11-15 17:34:31",
"updateBy": null,
"updateTime": null,
"remark": null,
"id": 164,
"taskName": "测试任务-想定演示",
"orderName": "du111506",
"duration": 10,
"beginYear": "2019",
"endYear": "2023",
}
],
selectdSingleItem: []
3. 对第一步中绑定的函数进行逻辑编写
// select-all绑定的函数
onSelectAll() {
// 当全部选中时通过refs找到对应组件,清空所有选中的数据
// 因为此刻是单选需求,全部选中的话是多选,因此当全部选中时要清空勾选项
this.$refs.multipleTable.clearSelection();
},
// row-click绑定的函数
onSelectOp(row) {
// 点击某一行时选中
// 因为是单选,当点击某一行时应该将之前点击行的选中取消 因此要清空所有选中
this.$refs.multipleTable.clearSelection();
// 当点击某一行时传值的row,判断点击哪行,将该行选中
this.$refs.multipleTable.toggleRowSelection(row, true);
},
// selection-change绑定的函数
handleSelectionChange(rows) {
// 当勾选的行数大于1个时 rows代表所勾选的数组
if (rows.length > 1) {
const newRows = rows.filter((it, index) => {
if (index == rows.length - 1) {
this.$refs.multipleTable.toggleRowSelection(it, true);
return true;
} else {
this.$refs.multipleTable.toggleRowSelection(it, false);
return false;
}
});
// 赋值给全局变量保存
this.selectdSingleItem = newRows;
} else {
// 当勾选行数小于一个时,将选中的值赋值给全局变量保存
this.selectdSingleItem = rows;
}
},