vue 实现表格单选
Vue 实现表格单选的方法
使用 v-model 绑定选中项
通过 v-model 绑定一个变量来记录当前选中的行数据。在表格的每一行添加单选按钮或点击事件来更新这个变量。

<template>
<table>
<tr v-for="item in tableData" :key="item.id" @click="selectedRow = item">
<td><input type="radio" :checked="selectedRow === item"></td>
<td>{{ item.name }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
],
selectedRow: null
}
}
}
</script>
使用计算属性优化
添加计算属性来判断当前行是否被选中,使模板更简洁。

<template>
<table>
<tr v-for="item in tableData" :key="item.id" @click="selectedRow = item"
:class="{ 'selected': isSelected(item) }">
<td><input type="radio" :checked="isSelected(item)"></td>
<td>{{ item.name }}</td>
</tr>
</table>
</template>
<script>
export default {
computed: {
isSelected() {
return (item) => this.selectedRow === item
}
}
}
</script>
使用第三方组件库
若使用 Element UI 等组件库,可直接利用其提供的单选表格功能。
<template>
<el-table
:data="tableData"
@current-change="handleCurrentChange"
highlight-current-row>
<el-table-column prop="name" label="Name"></el-table-column>
</el-table>
</template>
<script>
export default {
methods: {
handleCurrentChange(val) {
this.currentRow = val
}
}
}
</script>
添加样式反馈
为选中行添加视觉反馈,提升用户体验。
.selected {
background-color: #f0f0f0;
}
tr:hover {
cursor: pointer;
}
注意事项
- 确保每个数据项有唯一标识符(如 id)
- 考虑添加初始选中状态逻辑
- 移动端适配可能需要调整点击区域大小
- 大型表格需考虑性能优化





