vue表格实现单选框
Vue 表格实现单选框的方法
使用 el-table 和 el-radio 组件
在 Vue 项目中,结合 Element UI 的 el-table 和 el-radio 组件可以轻松实现表格中的单选框功能。以下是一个完整的实现示例:
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column label="选择" width="80">
<template #default="{ row }">
<el-radio v-model="selectedRow" :label="row.id">{{ '' }}</el-radio>
</template>
</el-table-column>
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
selectedRow: null,
tableData: [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 },
{ id: 3, name: '王五', age: 28 }
]
}
}
}
</script>
自定义单选逻辑
如果需要更灵活的控制,可以自定义单选逻辑:
<template>
<el-table :data="tableData" style="width: 100%" @row-click="handleRowClick">
<el-table-column label="选择" width="80">
<template #default="{ row }">
<el-radio :checked="selectedRow === row.id"></el-radio>
</template>
</el-table-column>
<!-- 其他列 -->
</el-table>
</template>
<script>
export default {
methods: {
handleRowClick(row) {
this.selectedRow = row.id
}
}
}
</script>
使用纯 CSS 实现单选样式
如果不依赖 Element UI,可以使用纯 CSS 实现表格单选效果:
<template>
<table class="radio-table">
<tr v-for="item in tableData"
:key="item.id"
:class="{ selected: selectedRow === item.id }"
@click="selectedRow = item.id">
<td><input type="radio" :checked="selectedRow === item.id"></td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</table>
</template>
<style>
.radio-table tr {
cursor: pointer;
}
.radio-table tr.selected {
background-color: #f5f7fa;
}
</style>
响应式单选实现
对于需要响应式处理的场景,可以添加计算属性:
computed: {
selectedItem() {
return this.tableData.find(item => item.id === this.selectedRow) || {}
}
}
这样可以通过 selectedItem 访问当前选中的行数据。

注意事项
- 确保每行数据有唯一标识符(如 id)
- 单选逻辑应清晰,避免与多选混淆
- 考虑添加空状态处理,当没有选中项时的显示
- 移动端适配可能需要调整点击区域大小
以上方法可根据具体项目需求选择或组合使用,Element UI 方案适合快速开发,自定义方案则提供更多灵活性。






