vue表格实现单选框
实现单选框的基本思路
在Vue中实现表格单选框,通常需要结合<table>和<input type="radio">元素,并通过v-model绑定选中状态。核心逻辑是确保同一时间只有一个选项被选中。
基础实现代码示例
<template>
<table>
<thead>
<tr>
<th>选择</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in tableData" :key="index">
<td>
<input
type="radio"
v-model="selectedRow"
:value="item.id"
>
</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</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>
使用组件库优化
如果使用Element UI等组件库,可以直接使用其提供的单选表格组件:
<template>
<el-table
:data="tableData"
@current-change="handleCurrentChange"
highlight-current-row
>
<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 {
tableData: [
{ name: '张三', age: 25 },
{ name: '李四', age: 30 },
{ name: '王五', age: 28 }
]
}
},
methods: {
handleCurrentChange(val) {
console.log('当前选中行:', val)
}
}
}
</script>
自定义样式和交互
可以通过CSS自定义单选按钮样式,并添加交互效果:
/* 隐藏原生单选按钮 */
input[type="radio"] {
appearance: none;
-webkit-appearance: none;
width: 16px;
height: 16px;
border: 1px solid #999;
border-radius: 50%;
outline: none;
cursor: pointer;
}
/* 选中状态样式 */
input[type="radio"]:checked {
background-color: #409EFF;
border-color: #409EFF;
}
/* 添加hover效果 */
tr:hover {
background-color: #f5f5f5;
}
完整功能实现
结合全选/反选功能和获取选中数据:

<template>
<div>
<button @click="clearSelection">清除选择</button>
<table>
<!-- 表格内容同上 -->
</table>
<p>当前选中ID: {{ selectedRow }}</p>
</div>
</template>
<script>
export default {
methods: {
clearSelection() {
this.selectedRow = null
},
getSelectedData() {
return this.tableData.find(item => item.id === this.selectedRow)
}
}
}
</script>
注意事项
- 确保每个单选按钮的
value值是唯一的,通常使用数据项的ID - 对于大量数据,考虑使用虚拟滚动优化性能
- 移动端适配可能需要调整单选按钮的大小和间距
- 如果表格有分页,需要处理跨页选中的状态保持问题






