【vue+element-ui】前端实现表格checkbox单选
需求:每次只能选中一条数据进行操作,如果同时选中多条,需弹出提示:请选择一条数据
那我就直接让它只能选中一条,不允许多选,上代码:
--------分割线---------
el-table组件中
<el-table ref="multipleTable" :data="tableData" @select="select" @select-all="selectAll">
写在methods中
select(selection, row) {
this.tableData.id = row.id
this.$refs.multipleTable.clearSelection();
if (selection.length == 0) return;
this.$refs.multipleTable.toggleRowSelection(row, true);
}
禁止全选
selectAll() {
this.$refs.multipleTable.clearSelection();
},
-------------------手动分割线-------------------------------------------------------------------------------------------------------
测试出bug:选择一项后,再选择一项时,提示没有只选择一条数据
console.log两次选择的selection.length,发现上一次点击的数据并没有被消除,改进如下:
<el-table ref="multipleTable" :data="tableData" @selection-change="handleSelectionChange" @select-all="selectAll">
handleSelectionChange(val) {
if (val.length === 0) {
return
} else if (val.length > 1) {
this.$refs.multipleTable.cleanSelected();
this.$refs.multipleTable.rowSelection(val[val.length - 1], true);
this.selectArr = []
this.selectArr.push(val[val.length - 1])
} else {
this.selectArr = val
}
},
当val.length为0 时,也就是没有选择数据,return
当val.length大于1时,也就是选择了多于1条数据,清除内容,将最近一条数据的值赋给selectArr,作为弹框的默认值
当val.length等于1时,也就是只选择1条数据,将val赋值给selectArr,作为弹框的默认值