CrudTable 数据表格
通过列表接口、列和动作配置,处理分页、选择、权限、排序及数据操作。在 CrudPage 中自动联动搜索和表单,以下示例用于独立使用。
基础用法
<template>
<CrudTable
ref="tableRef"
:table-config="tableConfig"
@create="openCreate"
@toggle-search="toggleSearch"
@filter-change="applyFilters"
@row-action="handleRowAction"
/>
</template>
<script setup lang="ts">
import UserAPI from "@/api/system/user";
import type { UserItem, UserQuery } from "@/api/system/user";
import type { CrudTableConfig } from "@/components/Crud/types";
const tableConfig: CrudTableConfig<UserQuery, UserItem> = {
permissionPrefix: "sys:user",
fetchData: UserAPI.getPage,
deleteByIds: UserAPI.deleteByIds,
toolbarActions: ["create", "delete"],
tableTools: ["refresh", "columns", "search"],
columns: [
{ type: "selection", width: 50 },
{ prop: "username", label: "用户名", hideable: false },
{ prop: "nickname", label: "昵称" },
{ prop: "createTime", label: "创建时间", sortable: "custom" },
{
prop: "actions",
label: "操作",
cellType: "actions",
width: 200,
fixed: "right",
actions: ["view", "edit", "delete"],
},
],
};
</script>每行需要稳定的字符串或数字主键,默认 id,其他名称配置 rowKey。表格默认自动首次查询;自行控制时设置 :auto-load="false" 再调用 loadData。
适配接口结果
fetchData(query) 返回 Promise<{ list, total }> 或数组,是接口与组件之间的适配层。返回其他结构时在回调中转换:
{
async fetchData(query) {
const result = await OrderAPI.getPage(query);
return { list: result.records, total: result.totalCount };
},
}不要重复取 data
项目请求拦截器已返回业务 data,调用本项目 API 后不要再取 .data。
无分页接口直接返回数组,并设置 pagination: false:
const tableConfig: CrudTableConfig = {
pagination: false,
rowKey: "value",
fetchData: RoleAPI.getOptions,
columns: [{ prop: "label", label: "角色" }],
};分页
默认参数名 pageNum、pageSize,页码从 1 开始,每页 20 条:
{
pagination: { pageSize: 10, pageSizes: [10, 20, 50] },
// 接口参数名不同时才需要配置
paginationKeys: { page: "page", size: "limit" },
}pagination: false 隐藏分页,组件不对数组返回值切片。删除末页最后一条后自动回到有效页。
按钮与权限
toolbarActions 配置左侧业务按钮,tableTools 配置右侧圆形工具,未配置时不显示。
内置动作
| 动作 | 位置 | 默认权限后缀 | 行为 |
|---|---|---|---|
| create | 工具栏 | create | 打开新增表单 |
| delete | 工具栏 / 行 | delete | 批量或单条删除,自带确认 |
| import / export | 工具栏 | import / export | 按配置导入导出 |
| edit | 行 | update | 打开编辑表单 |
| view | 行 | update | 打开只读表单 |
| search | 工具 | list | 切换搜索区域 |
| refresh / columns | 工具 | 无限制 | 刷新、列显隐 |
配置 permissionPrefix 后,内置动作自动拼接权限(如 sys:user:create);未配置前缀时不校验业务权限。view 默认使用 update 权限,有独立详情权限时用 permission 覆盖。
自定义动作
字符串之外,动作也可以是对象:
{
key: "enable",
label: "启用",
permission: "sys:user:update",
visible: ({ row }) => row?.status === 0,
async onClick({ row }) {
if (!row) return;
await UserAPI.updateStatus(String(row.id), 1);
},
}| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| key | 动作标识,也用于按钮插槽 | string | — |
| label | 按钮文字 | string | 内置默认 |
| permission | 完整权限、相对后缀或数组 | string | string[] | 内置默认 |
| visible | 显示条件 | boolean | (ctx) => boolean | true |
| disabled | 禁用条件 | boolean | (ctx) => boolean | false |
| buttonProps | Element Plus Button 属性 | ButtonProps | — |
| onClick | 自定义操作,返回 Promise 时按钮等待完成 | (ctx) => void | Promise | — |
上下文 ctx 包含 row?、selectedRows、selectedKeys,工具栏动作没有 row。权限数组为任一满足语义。相对后缀与前缀组合,完整权限(含 :)可跨模块。
批量操作配置 disabled: ({ selectedKeys }) => selectedKeys.length === 0。批量删除未勾选时自动禁用。
操作列折叠
行操作超过 3 个时,前 3 个直接显示,其余收进"更多"。maxVisibleActions 调整上限,0 表示全部显示。权限不足或 visible: false 的动作先排除,禁用动作仍占位。
列配置
列支持 Element Plus TableColumn 属性(width、minWidth、fixed、align、formatter、filters 等),额外属性:
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| show | 默认是否显示 | boolean | true |
| hideable | 设为 false 时用户不能在列设置中隐藏 | boolean | true |
| cellType | 单元格模板,见下表 | string | — |
| actions | 动作列的按钮 | Array<string | CrudAction> | ['edit', 'delete'] |
| maxVisibleActions | 直接显示的操作上限 | number | 3 |
| columnKey | 表头筛选参数名 | string | prop |
| filterJoin | 筛选数组转字符串的分隔符 | string | — |
| sortField | 远程排序的 API 属性名 | string | prop |
| onInit | 一次性初始化,支持 Promise | (column) => void | Promise | — |
cellType 单元格模板
| 值 | 展示 | 相关属性 |
|---|---|---|
| image | 图片,支持数组多图预览 | imageWidth、imageHeight(默认 40) |
| list | 值映射为文本 | selectList,如 { 1: "启用" } |
| url | 新窗口打开的链接 | — |
| switch | 开关,切换即保存 | activeValue、inactiveValue、activeText、inactiveText |
| input | 输入框,失焦即保存 | inputType |
| price | 金额前缀 | priceFormat,如 ¥ |
| percent | 百分号后缀 | — |
| icon | 图标,支持 el-icon-* 和 UnoCSS svg | — |
| date | 格式化日期 | dateFormat(默认 YYYY-MM-DD HH:mm:ss) |
| actions | 行操作按钮 | actions、maxVisibleActions |
| custom | 自定义插槽 | slotName,默认 prop |
switch 和 input 需配置 updateField 才可编辑,见单元格即时编辑。右侧 columns 工具提供列显隐和恢复默认,状态仅保存在当前实例。
排序
{
table: { defaultSort: { prop: "createTime", order: "descending" } },
columns: [{ prop: "createTime", label: "创建时间", sortable: "custom" }],
}sortable: true:本地排序,仅作用于已加载行sortable: "custom":远程排序,回到第一页,参数为sort=createTime,desc- 取消排序不发送
sort;展示属性与 API 属性不同时配置sortField
排序参数采用 Spring Data 约定,允许的字段由后端校验。
表头筛选
列配置 filters 和 columnKey,绑定 @filter-change="applyFilters" 后沿用已应用的搜索条件查询:
{
prop: "roleNames",
columnKey: "roleIds",
label: "角色",
filterJoin: ",",
async onInit(column) {
column.filters = (await RoleAPI.getOptions()).map((role) => ({
text: role.label,
value: role.value,
}));
},
}取消某列筛选后,该条件从查询和导出中删除。重置搜索会清除表头筛选,保留排序。
单元格即时编辑
配置 updateField 后,switch 切换、input 失焦时保存单字段;缺少回调或 update 权限时禁用:
{
async updateField({ id, field, value }) {
if (field !== "status" || (value !== 0 && value !== 1)) {
throw new Error("不支持的修改");
}
await UserAPI.updateStatus(String(id), value);
},
}回调收到 { [rowKey]: id, field, value }。相同值不提交,失败自动回滚。多字段统一保存请使用表单。
API
Attributes
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| table-config | 表格配置 | CrudTableConfig | — |
| auto-load | 是否自动首次查询 | boolean | true |
TableConfig
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| fetchData | 列表查询,返回分页结果或数组 | (query) => Promise<PageResult | T[]> | — |
| columns | 列配置 | Column[] | — |
| rowKey | 主键名 | string | id |
| permissionPrefix | 权限前缀,如 sys:user | string | — |
| table | Element Plus Table 属性 | TableProps | — |
| pagination | 分页属性,false 隐藏 | boolean | PaginationProps | 每页 20 条 |
| pagePosition | 分页位置 | 'left' | 'right' | left |
| paginationKeys | 分页参数名 | { page, size } | pageNum / pageSize |
| toolbarActions | 左侧业务按钮 | Array<string | CrudAction> | — |
| tableTools | 右侧工具 | Array<string | CrudAction> | — |
| deleteByIds | 删除接口,主键逗号拼接 | (ids: string) => Promise | — |
| updateField | 单字段保存接口 | (data) => Promise | — |
| importFile / importRows | 导入回调,见导入导出 | Function | — |
| exportFile / fetchExportRows | 导出回调,见导入导出 | Function | — |
| importTemplate | 导入模板 URL 或下载函数 | string | () => Promise | — |
| importMode / exportMode | 同时提供两种回调时必选 | 'file' | 'rows' | — |
Events
| 事件名 | 说明 | 回调参数 |
|---|---|---|
| create | 点击新增 | — |
| toggle-search | 点击搜索工具 | — |
| toolbar-action | 未配置 onClick 的自定义工具栏动作 | key: string |
| filter-change | 表头筛选变化 | filters: CrudRecord |
| row-action | 自定义行操作 | { key, row } |
Slots
| 插槽名 | 说明 | 参数 |
|---|---|---|
| cell- | 单元格,优先于 cellType | { row, column, $index, prop } |
| header- | 表头 | Element Plus 表头作用域 |
| row-action- | 行操作按钮 | { row, action, overflow } |
| toolbar-action- | 工具栏按钮 | { action } |
| cellType 为 custom 时的单元格 | { row, column, $index, prop } |
自定义按钮通过 action.run() 执行并绑定状态,保留权限复查、防重复点击和失败反馈:
<template #row-action-enable="{ action }">
<el-button
v-bind="action.buttonProps"
:disabled="action.disabled"
:loading="action.loading"
@click="action.run()"
>
{{ action.label }}
</el-button>
</template>action 包含 key、label、buttonProps、disabled、loading、run;overflow 表示按钮位于"更多"浮层。
Exposes
| 名称 | 说明 | 类型 |
|---|---|---|
| loadData | 应用条件并查询 | (params?, resetPage?) => Promise<void> |
| refresh | 沿用已应用条件刷新 | (resetPage?) => Promise<void> |
| getSelection | 读取勾选的行 | () => CrudRecord[] |
| getFilters | 读取表头筛选条件 | () => CrudRecord |
| getExportQuery | 上次成功查询的条件,不含分页 | () => CrudRecord |
| clearFilters | 清除筛选,不发起查询 | () => void |
| exportFile | 执行服务端文件导出 | () => Promise<void> |
查询失败
仅最新请求可以更新列表;失败保留已有行并显示错误。未成功加载或查询失败时禁止导出。直接调用 loadData、refresh 时由调用方处理 Promise 拒绝。
