vue表格实现单选
实现 Vue 表格单选功能
在 Vue 中实现表格单选功能可以通过以下方法完成,核心思路是绑定选中状态并监听用户操作。
方法一:使用 v-model 绑定选中行
通过 v-model 绑定一个变量存储当前选中行的数据,结合 @click 事件切换选中状态。

<template>
<table>
<tr v-for="(item, index) in tableData" :key="index"
@click="selectedRow = item"
:class="{ 'selected': selectedRow === item }">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
],
selectedRow: null
};
}
};
</script>
<style>
.selected {
background-color: #f0f0f0;
}
</style>
方法二:使用计算属性动态判断选中状态
通过计算属性或方法判断当前行是否为选中状态,适用于需要复杂逻辑的场景。

<template>
<table>
<tr v-for="(item, index) in tableData" :key="index"
@click="selectRow(item)"
:class="{ 'selected': isSelected(item) }">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
],
selectedRow: null
};
},
methods: {
selectRow(item) {
this.selectedRow = item;
},
isSelected(item) {
return this.selectedRow === item;
}
}
};
</script>
方法三:结合第三方表格组件(如 Element UI)
如果使用 Element UI 的 el-table 组件,可以直接利用其内置的单选功能。
<template>
<el-table
:data="tableData"
@current-change="handleCurrentChange"
highlight-current-row>
<el-table-column prop="name" label="Name"></el-table-column>
<el-table-column prop="age" label="Age"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
]
};
},
methods: {
handleCurrentChange(val) {
console.log('当前选中行:', val);
}
}
};
</script>
关键点说明
- 数据绑定:通过
selectedRow变量存储当前选中行的数据。 - 样式反馈:通过 CSS 类名(如
.selected)或组件内置属性(如highlight-current-row)高亮选中行。 - 事件监听:使用
@click或@current-change监听用户操作并更新选中状态。
以上方法均能实现表格单选功能,可根据项目需求选择原生实现或结合第三方组件库。






