vue实现表格的单选
Vue 实现表格单选功能
在 Vue 中实现表格的单选功能,可以通过以下方法完成。这里以 Element UI 的表格组件为例,但原理同样适用于其他 UI 库或原生表格。
方法一:使用 Element UI 的表格单选功能
Element UI 的 el-table 组件内置了单选功能,可以通过 highlight-current-row 属性开启高亮当前行,并通过 @current-change 事件获取选中行数据。

<template>
<el-table
:data="tableData"
highlight-current-row
@current-change="handleCurrentChange"
style="width: 100%">
<el-table-column
prop="name"
label="姓名">
</el-table-column>
<el-table-column
prop="age"
label="年龄">
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20 },
{ name: '李四', age: 25 },
{ name: '王五', age: 30 }
],
currentRow: null
}
},
methods: {
handleCurrentChange(val) {
this.currentRow = val
}
}
}
</script>
方法二:自定义单选逻辑
如果需要更灵活的控制,可以手动实现单选逻辑。例如,通过点击行时切换选中状态。

<template>
<table>
<tr
v-for="(item, index) in tableData"
:key="index"
@click="selectRow(index)"
:class="{ 'selected': selectedIndex === index }">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20 },
{ name: '李四', age: 25 },
{ name: '王五', age: 30 }
],
selectedIndex: -1
}
},
methods: {
selectRow(index) {
this.selectedIndex = index
}
}
}
</script>
<style>
.selected {
background-color: #f0f0f0;
}
</style>
方法三:使用单选按钮
另一种常见的方式是在每行添加单选按钮,通过绑定 v-model 实现单选。
<template>
<table>
<tr v-for="(item, index) in tableData" :key="index">
<td>
<input
type="radio"
:value="index"
v-model="selectedIndex">
</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20 },
{ name: '李四', age: 25 },
{ name: '王五', age: 30 }
],
selectedIndex: -1
}
}
}
</script>
方法四:使用 Vuex 管理选中状态
如果需要在多个组件间共享选中状态,可以使用 Vuex 管理。
// store.js
export default new Vuex.Store({
state: {
selectedRow: null
},
mutations: {
setSelectedRow(state, row) {
state.selectedRow = row
}
}
})
<template>
<el-table
:data="tableData"
highlight-current-row
@current-change="handleCurrentChange">
<!-- 表格列定义 -->
</el-table>
</template>
<script>
import { mapMutations } from 'vuex'
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20 },
{ name: '李四', age: 25 },
{ name: '王五', age: 30 }
]
}
},
methods: {
...mapMutations(['setSelectedRow']),
handleCurrentChange(row) {
this.setSelectedRow(row)
}
}
}
</script>
以上方法可以根据具体需求选择使用。Element UI 的内置功能适合快速实现,自定义逻辑则提供更大的灵活性。






