el-table实现单选功能
利用Element-UI组件中的el-table实现选择功能,官方提供了两种选择方式,一种是单选,一种是多选。我需要实现单选的效果
第一步:监听checkbox 的点击事件(选中和取消选中)
<el-table
:data="tableData"
ref="myTable"
stripe border
row-key="id"
:header-cell-style="headerClass"
:cell-style="cellClass"
@selection-change="handleSelectionChange"
>
<!-- 出现多选模式的selection选择框 只需要加上以下一行就可以 -->
<el-table-column type="selection" width="50" align="center"></el-table-column>
<el-table-column label="权限名称" width="160px">
<template slot-scope="scope">
<svg-icon icon-class="role2" :style="{ color: scope.row.iconColor ? scope.row.iconColor : '#000000' }"></svg-icon>
<span>{{ scope.row.roleName }}</span>
</template>
</el-table-column>
<el-table-column label="权限描述" prop="remark" show-overflow-tooltip> </el-table-column>
</el-table>
第二步:利用el-table提供的方法处理数据
selectionChange(row) {
// console.log("🚀 ~ selectionChange ~ row:", row);
// this.selectionRowList = row;
// if (row.length > 1) {
// // 如果选择超过一个选项,则只保留最后一个选项
// row.splice(0, row.length - 1);
// }
this.selectionRowList = row;
if (row.length > 1) {
this.$refs.myTable.clearSelection();
this.$refs.myTable.toggleRowSelection(row.pop());
}
if (row.length != 0) {
this.selectProtocolId = row[row.length - 1].id;
}
},
解释一下上面的这个函数,
selectionRowList 用来接收选中的行数据,最后需要返回给父元素,
selectProtocolId 用来解决数据回显的问题,第三步会讲到这一步为什么要修改
clearSelection 用来清除所有选中的数据
toggleRowSelection 用来切换某一行的状态,参数是某行的整条数据
这样就能简单的利用多选模式的样式来实现单选
第三步:数据回显
上面两步已经能实现基本功能,这一步解决的是回显的问题。选中数据后,想要再次修改,存在一些小小的坑
item.id去取当前数据的唯一id值就好,注意放置的顺序!!!!!!!
this.tableData.forEach((item,index) => {
if(item.id == this.selectProtocolId){
this.$nextTick(() => {
this.$refs.myTable.toggleRowSelection(item);
})
}
})
想要展示选中的数据,首先得与数据源进行比较,tableData是分页拿到的数据。
selectProtocolId的初始值是props中传递过来的一个参数(无法修改props属性的值,只能用一个中间变量来控制),代表上一次保存的数据。往后每次点击切换的时候,都需要动态的更新这个值(第二步中提到的内容),否则就会出现某两页都有数据被选中的情况,因为不改变selectProtocolId的值,总会有某页的某条数据与之匹配
$nextTick确保在DOM更新时切换数据选中状态的代码能正常执行,否则直接执行,无法设置选中状态
第四步:禁用全选功能
::v-deep .el-table__header-wrapper .el-checkbox{
//找到表头那一行,然后把里面的复选框隐藏掉
display:none
}
推荐阅读:
扫描二维码,在手机上阅读