vue实现单选表格
实现单选表格的基本思路
在Vue中实现单选表格需要结合表格组件和单选逻辑。通常使用<table>元素或第三方UI库(如Element UI、Ant Design Vue)的表格组件,通过v-model或自定义事件管理选中状态。
使用原生HTML表格实现
<template>
<table>
<thead>
<tr>
<th>选择</th>
<th>ID</th>
<th>名称</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id" @click="selectRow(item)">
<td>
<input
type="radio"
:checked="selectedItem && selectedItem.id === item.id"
@click.stop
/>
</td>
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: '项目A' },
{ id: 2, name: '项目B' },
{ id: 3, name: '项目C' }
],
selectedItem: null
}
},
methods: {
selectRow(item) {
this.selectedItem = item
}
}
}
</script>
使用Element UI实现
安装Element UI后,可通过el-table和单选列快速实现:
<template>
<el-table
:data="tableData"
@current-change="handleCurrentChange"
highlight-current-row
>
<el-table-column prop="id" label="ID" />
<el-table-column prop="name" label="名称" />
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: '项目A' },
{ id: 2, name: '项目B' },
{ id: 3, name: '项目C' }
]
}
},
methods: {
handleCurrentChange(val) {
console.log('当前选中:', val)
}
}
}
</script>
使用Ant Design Vue实现
安装Ant Design Vue后,通过a-table和自定义选择逻辑实现:
<template>
<a-table
:columns="columns"
:data-source="tableData"
:row-selection="rowSelection"
/>
</template>
<script>
const columns = [
{ title: 'ID', dataIndex: 'id' },
{ title: '名称', dataIndex: 'name' }
]
export default {
data() {
return {
tableData: [
{ id: 1, name: '项目A' },
{ id: 2, name: '项目B' },
{ id: 3, name: '项目C' }
],
selectedRowKeys: []
}
},
computed: {
rowSelection() {
return {
type: 'radio',
selectedRowKeys: this.selectedRowKeys,
onChange: keys => {
this.selectedRowKeys = keys
}
}
}
}
}
</script>
自定义单选逻辑实现
对于需要更复杂控制的场景,可手动管理选中状态:
<template>
<table>
<tr
v-for="item in tableData"
:key="item.id"
:class="{ 'active': selectedId === item.id }"
@click="selectedId = item.id"
>
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [...],
selectedId: null
}
}
}
</script>
<style>
.active {
background-color: #f0f0f0;
}
</style>
性能优化建议
对于大数据量表格,建议:
- 使用虚拟滚动(如vue-virtual-scroller)
- 避免在模板中进行复杂计算
- 使用
Object.freeze冻结静态数据 - 考虑分页加载
以上方法可根据项目需求和技术栈选择最适合的实现方式。第三方UI库通常提供更丰富的功能和样式支持,而原生实现则更灵活可控。







