开发避坑指南(42):Vue3 element ui el-table单选实现方案
需求
Vue3+element ui el-table如何实现表格行单选功能?
原代码
<el-table ref="mutiTable" v-loading="loading" :data="orderList" ><el-table-column type="selection" width="55" align="center" /><el-table-column label="序号" align="center" width="80"><template #default="scope">{{ scope.$index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}</template></el-table-column>
</el-table>
官方提供了单选的功能,但是没有单选框或者只能单选的复选框,单选不够明显。
解决方法
(1)el-table 增加highlight-current-row 属性,绑定@row-dblclick 事件,绑定@current-change事件
(2)删除type="selection"的el-table-column,增加el-radio的el-table-column
(3)定义currentRow变量、handleMutiTableRowClick()函数、handleCurrentChange()函数
页面代码如下:
<el-table ref="mutiTable" v-loading="loading" :data="orderList" highlight-current-row @row-dblclick="handleMutiTableRowClick"@current-change="handleCurrentChange"><el-table-column width="35"><template v-slot="scope"><el-radioclass="radio":label="scope.row"v-model="currentRow" >{{""}}</el-radio></template></el-table-column><el-table-column label="序号" align="center" width="80"><template #default="scope">{{ scope.$index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}</template></el-table-column>
</el-table>
变量定义:
const currentRow = ref();
函数:
function handleCurrentChange(row) {currentRow.value = row;//可添加其他行事件,如禁用启用操作按钮
}
function handleMutiTableRowClick(row, column, event) { if (currentRow && row.value.orderNo == currentRow.value.orderNo) { setCurrent();currentRow.value= null; } else {currentRow.value = row;}
}
function setCurrent(row) {proxy.$refs["mutiTable"].setCurrentRow(row);
}