vue表格实现单选
Vue 表格实现单选的方法
使用 v-model 绑定选中状态
通过 v-model 绑定一个变量来记录当前选中的行数据,结合 v-for 渲染表格时动态设置选中样式。
<template>
<table>
<tr v-for="item in tableData" :key="item.id"
@click="selectedRow = item"
:class="{ 'active': selectedRow === item }">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
],
selectedRow: null
};
}
};
</script>
<style>
.active {
background-color: #f0f0f0;
}
</style>
使用单选框(Radio Button)
在表格每行前加入单选框,通过 v-model 绑定选中的值。
<template>
<table>
<tr v-for="item in tableData" :key="item.id">
<td><input type="radio" v-model="selectedId" :value="item.id"></td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
],
selectedId: null
};
}
};
</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: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
]
};
},
methods: {
handleCurrentChange(val) {
console.log('当前选中行:', val);
}
}
};
</script>
注意事项
- 若需默认选中某一行,可在
data中初始化selectedRow或selectedId为对应值。 - 高亮样式可通过 CSS 自定义,如背景色、边框等。
- 第三方组件(如 Element UI)可能提供更多扩展功能,如禁用某些行的单选。





