useTableSelection 表格选择
表格行选择管理,统一处理选中 ID 列表、选择变化和清空。
基础用法
vue
<template>
<el-table :data="tableData" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="50" />
<el-table-column prop="name" label="姓名" />
<el-table-column prop="email" label="邮箱" />
</el-table>
<div class="toolbar">
<span>已选择 {{ selectedCount }} 条</span>
<el-button :disabled="!hasSelection" @click="handleBatchDelete">批量删除</el-button>
<el-button @click="clearSelection">清空选择</el-button>
</div>
</template>
<script setup lang="ts">
import { useTableSelection } from '@/composables'
interface UserVO {
id: number
name: string
email: string
}
const tableData = ref<UserVO[]>([])
const {
selectedIds,
selectedCount,
hasSelection,
handleSelectionChange,
clearSelection,
} = useTableSelection<UserVO>()
async function handleBatchDelete() {
if (!hasSelection.value) {
ElMessage.warning('请选择要删除的数据')
return
}
await UserAPI.deleteByIds(selectedIds.value)
ElMessage.success('删除成功')
clearSelection()
fetchData()
}
</script>返回值
| 名称 | 类型 | 说明 |
|---|---|---|
selectedIds | Ref<(string | number)[]> | 选中的 ID 数组 |
selectedCount | ComputedRef<number> | 选中的数量 |
hasSelection | ComputedRef<boolean> | 是否有选中项 |
handleSelectionChange | (selection: T[]) => void | 处理选择变化 |
clearSelection | () => void | 清空选择 |
isSelected | (id) => boolean | 检查是否选中 |
泛型约束
数据项类型必须包含 id 属性:
typescript
interface UserVO {
id: number
name: string
}
const { selectedIds } = useTableSelection<UserVO>()主键不是 id 时,可在处理函数中手动转换:
typescript
interface OrderVO {
orderId: string
orderNo: string
}
const selectedOrderIds = ref<string[]>([])
function handleSelectionChange(selection: OrderVO[]) {
selectedOrderIds.value = selection.map(item => item.orderId)
}跨页选择
配合 row-key 和 reserve-selection:
vue
<el-table
:data="tableData"
:row-key="row => row.id"
@selection-change="handleSelectionChange"
>
<el-table-column type="selection" width="50" :reserve-selection="true" />
</el-table>