vue实现单选表格
实现单选表格的基本思路
在Vue中实现单选表格通常需要结合<table>元素和Vue的数据绑定特性。通过v-model或自定义事件管理选中状态,确保同一时间仅有一行被选中。

使用v-model绑定选中状态
定义数据对象存储当前选中行的唯一标识(如ID),结合v-model或v-bind:checked实现单选逻辑。

<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 {
selectedId: null,
tableData: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
]
};
},
methods: {
handleSelect(item) {
console.log('选中行:', item);
}
}
};
</script>
通过事件手动控制选中状态
若需更灵活的控制(如避免使用v-model),可通过点击事件动态更新选中状态。
<template>
<table>
<tr
v-for="item in tableData"
:key="item.id"
@click="selectRow(item.id)"
:class="{ 'selected': selectedId === item.id }"
>
<td>
<input
type="radio"
:checked="selectedId === item.id"
@click.stop
>
</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
selectedId: null,
tableData: [/* 数据同上 */]
};
},
methods: {
selectRow(id) {
this.selectedId = id;
}
}
};
</script>
<style>
.selected {
background-color: #f0f0f0;
}
</style>
使用第三方组件库(如Element UI)
若项目中使用Element UI,可直接利用其<el-table>组件的单选功能。
<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: [/* 数据同上 */]
};
},
methods: {
handleCurrentChange(val) {
console.log('当前选中行:', val);
}
}
};
</script>
关键注意事项
- 唯一标识:确保每行数据有唯一
id或其他标识字段。 - 性能优化:大数据量时考虑虚拟滚动(如使用
vue-virtual-scroller)。 - 无障碍访问:为单选按钮添加
aria-label或通过<label>关联文本。
通过上述方法,可灵活实现符合业务需求的单选表格功能。






