vue表格实现单选
实现 Vue 表格单选功能
使用 v-model 绑定选中状态
在表格的每一行添加单选按钮或点击行触发选中,通过 v-model 绑定一个变量存储当前选中行的唯一标识(如 id)。
示例代码:

<template>
<table>
<tr v-for="item in tableData" :key="item.id" @click="selectedId = item.id">
<td><input type="radio" v-model="selectedId" :value="item.id"></td>
<td>{{ item.name }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
],
selectedId: null
};
}
};
</script>
高亮选中行样式
通过动态类名或样式绑定,为选中行添加视觉反馈。
示例:
<tr
v-for="item in tableData"
:key="item.id"
@click="selectedId = item.id"
:class="{ 'active-row': selectedId === item.id }"
>
使用第三方表格组件(如 Element UI)
若使用 Element UI 的 el-table,可通过 highlight-current-row 属性实现单选高亮:
<el-table
:data="tableData"
highlight-current-row
@current-change="handleCurrentChange"
>
<el-table-column prop="name" label="Name"></el-table-column>
</el-table>
<script>
export default {
methods: {
handleCurrentChange(val) {
this.selectedRow = val; // val 为当前选中行数据
}
}
};
</script>
注意事项
- 确保每行数据有唯一标识(如
id),用于区分选中状态。 - 若需默认选中某一行,可在
data中初始化selectedId或selectedRow。 - 避免直接操作 DOM,优先通过 Vue 的数据驱动方式更新状态。







