vue表格实现单选框
实现单选框的基本思路
在Vue中实现表格单选框通常结合<input type="radio">或第三方组件库(如Element UI、Ant Design Vue等)。核心逻辑是通过v-model绑定选中状态,并通过遍历数据动态渲染表格行。

使用原生HTML实现
假设表格数据为tableData,选中项绑定到selectedItem:
<template>
<table>
<thead>
<tr>
<th>选择</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td>
<input
type="radio"
:value="item.id"
v-model="selectedId"
@change="handleSelect(item)"
>
</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 }
],
selectedId: null
};
},
methods: {
handleSelect(item) {
console.log('选中项:', item);
}
}
};
</script>
使用Element UI实现
若使用Element UI的el-table组件:
<template>
<el-table :data="tableData" @row-click="handleRowClick">
<el-table-column width="50">
<template #default="{ row }">
<el-radio
v-model="selectedId"
:label="row.id"
@change="handleSelect(row)"
></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 {
tableData: [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 }
],
selectedId: null
};
},
methods: {
handleSelect(item) {
console.log('选中项:', item);
},
handleRowClick(row) {
this.selectedId = row.id;
}
}
};
</script>
关键注意事项
- 唯一标识:确保每行数据有唯一
id,用于v-model绑定。 - 性能优化:大数据量时建议使用虚拟滚动(如
el-table内置优化)。 - 样式调整:通过CSS调整单选框对齐或间距,例如:
.el-radio { margin: 0; vertical-align: middle; }
扩展功能
- 默认选中:初始化时设置
selectedId为某一项的id。 - 禁用选项:通过
:disabled条件控制某些行不可选:<el-radio :disabled="row.disable" ...></el-radio>
以上方案可根据实际需求组合或调整,核心逻辑是通过响应式数据管理选中状态。







