el表格的单选
功能描述
实现表格的单选功能,包括复选框单选和行点击单选,并支持行高亮显示。
IMPORTANT
复选框单选
loading
IMPORTANT
单选框单选
loading
实现方案
表格配置
html
<el-table :data="tableData" @current-change="handleSelectionChange" highlight-current-row :cell-style="{ cursor: 'pointer' }">
<!-- 选择列 -->
<el-table-column width="55" align="center" label="选择">
<template #default="{ row }">
<el-checkbox v-model="row.checked" @change="handleSelectionChange(row)"> </el-checkbox>
</template>
</el-table-column>
<!-- 其他列配置... -->
</el-table>
<!-- ----------------------------------------------------------------- -->
<!-- 单选按钮 -->
<!-- 选择列:单选按钮 -->
<el-table-column width="55" align="center" label="选择">
<template #default="{ row }">
<el-radio :model-value="selection && selection.id" :value="row.id" @change="() => handleSelectionChange(row)" />
</template>
</el-table-column>
属性说明
highlight-current-row
: 开启行高亮效果:cell-style="{ cursor: 'pointer' }"
: 设置鼠标悬停样式为小手@current-change
: 行点击事件
数据处理
javascript
// 初始化表格数据,为每行添加 checked 属性
this.tableData = rows.map(item => ({ ...item, checked: false }))
选择处理函数
选项式 API
javascript
export default {
data() {
return {
selection: null,
tableData: []
}
},
methods: {
handleSelectionChange(selection) {
// 处理数组情况
if (selection instanceof Array) selection = selection[0]
// 更新选中状态
this.tableData.forEach(item => {
item.checked = item.id === selection?.id
})
this.selection = selection
}
}
}
组合式 API
javascript
import { ref } from 'vue'
const selection = ref(null)
const tableData = ref([])
// 复选框方案-单选处理:支持复选框和行点击
function handleSelectionChange(sel) {
// 处理数组情况(如@current-change传递的是数组)
if (sel instanceof Array) sel = sel[0]
// 更新checked状态,保证只有一行被选中
tableData.value.forEach(item => {
item.checked = item.id === sel?.id
})
selection.value = sel
}
// 单选按钮方案-单选处理:支持单选按钮和行点击
function handleSelectionChange(sel) {
// 处理数组情况(如@current-change传递的是数组)
if (sel instanceof Array) sel = sel[0]
selection.value = sel
}
注意事项
- 确保表格数据中每条记录都有唯一的
id
字段 - 初始化数据时需要添加
checked
属性 - 选中项保存在
selection
中,可用于后续操作