vue实现表格的单选
Vue 实现表格单选功能
在 Vue 中实现表格单选功能可以通过多种方式完成,以下是一种常见的实现方法。
使用 v-model 绑定选中项
通过 v-model 绑定一个变量来记录当前选中的行数据。在表格的每一行添加单选按钮或点击事件来更新选中状态。
<template>
<table>
<thead>
<tr>
<th>选择</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in tableData"
:key="item.id"
@click="selectRow(item)"
:class="{ 'selected': selectedItem === item }"
>
<td>
<input
type="radio"
:checked="selectedItem === item"
@click.stop="selectRow(item)"
/>
</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 },
{ id: 3, name: '王五', age: 28 }
],
selectedItem: null
};
},
methods: {
selectRow(item) {
this.selectedItem = item;
}
}
};
</script>
<style>
.selected {
background-color: #f0f0f0;
}
</style>
通过计算属性判断选中状态
利用计算属性或方法动态判断当前行是否被选中,减少模板中的逻辑。
<template>
<table>
<thead>
<tr>
<th>选择</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr
v-for="item in tableData"
:key="item.id"
@click="selectRow(item)"
:class="{ 'selected': isSelected(item) }"
>
<td>
<input
type="radio"
:checked="isSelected(item)"
@click.stop="selectRow(item)"
/>
</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 },
{ id: 3, name: '王五', age: 28 }
],
selectedItem: null
};
},
methods: {
selectRow(item) {
this.selectedItem = item;
},
isSelected(item) {
return this.selectedItem === item;
}
}
};
</script>
使用第三方表格组件
如果使用 Element UI 或 Ant Design Vue 等第三方组件库,可以更方便地实现单选功能。以下是 Element UI 的示例:
<template>
<el-table
:data="tableData"
@row-click="handleRowClick"
highlight-current-row
>
<el-table-column label="姓名" prop="name"></el-table-column>
<el-table-column label="年龄" prop="age"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 },
{ id: 3, name: '王五', age: 28 }
]
};
},
methods: {
handleRowClick(row) {
console.log('选中行:', row);
}
}
};
</script>
关键点总结
- 使用
v-model或变量绑定选中状态。 - 通过点击事件或单选按钮更新选中项。
- 高亮选中行可以通过 CSS 或组件库内置功能实现。
- 第三方组件库(如 Element UI)提供更便捷的单选支持。







