使用的是vue3+element-plus的技术栈
在说单选之前,先说下多选怎么实现:
实现多选非常简单: 手动添加一个
el-table-column,设type属性为selection即可;
<el-table ref="multipleTableRef" :data="tableData">
<el-table-column type="selection" :selectable="selectable" width="55" />
......
</el-table>
这样就实现了一个可以多选的表格.
接下来是单选,先说下思路,用到current-change触发事件,它会传入currentRow和oldCurrentRow两个参数,然后在首列渲染一个checkbox,判断当前选中的currentRow跟本身的row是否一致,来进行勾选.
<template>
<el-table :data="tableData" @current-change="handleCurrentChange">
<el-table-column :formatter="formatSelect" />
<el-table-column prop="date" label="Date" width="180" />
<el-table-column prop="name" label="Name" width="180" />
</el-table>
</template>
<script setup>
import {ref, h} from 'vue';
import { ElCheckbox } from 'element-plus';
const handleCurrentChange = (val) => {
curSelectRow.value = val;
};
const formatSelect = (row) => {
return h(
ElCheckbox,
{
modelValue: row === curSelectRow.value ? true : false,
}
);
};
const tableData = ref([
{
date: "2016-05-02",
name: "Tom",
},
{
date: "2016-05-04",
name: "Ruby",
},
]); // 表格数据
</script>
结语
以上就是实现表格单选的方式,element-plus官方也给出了的是使用highlight-current-row高亮跟current-change触发函数记录的方式,但是我想要的是有checkbox看着更直观,所以用h函数去动态生成,ok,关于表格实现单选框效果的文章就到这,主要是分享一下解题的思路,那就bye~~