Files
djangoadmin-wiki/DjangoAdmin_Flask_AntdVue/zh/volume4/frontend/table.md
T
2026-09-13 21:53:16 +08:00

8.7 KiB
Raw Blame History

BasicTable 表格

:::tip 说明 BasicTable 位于 src/components/Table/src/Table.vue,基于 AntDesign Vue 的 a-table 二次封装,提供列定义、数据请求、分页、多选、全屏、密度调整、列设置等能力。 :::

组件架构

src/components/Table/
├── src/
│   ├── Table.vue            # 主组件
│   ├── props.ts             # 属性定义
│   ├── types/table.ts       # 类型定义
│   ├── hooks/
│   │   ├── useLoading.ts      # loading 状态
│   │   ├── useColumns.ts      # 列管理
│   │   ├── useDataSource.ts   # 数据源管理
│   │   ├── usePagination.ts   # 分页管理
│   │   └── useTableContext.ts # 表格上下文
│   └── components/
│       ├── TableAction.vue    # 操作列按钮组件
│       └── settings/
│           └── ColumnSetting.vue    # 列设置面板
└── index.ts               # 导出 TableAction 等

基本用法

<BasicTable
    :columns="columns"
    :request="loadDataTable"
    :row-key="(row) => row.id"
    ref="tableRef"
    scroll-x="1200"
    :row-selection="{ onChange: onSelectionChange }"
>
    <template #tableTitle>
        <a-space>
            <a-button type="primary" @click="handleAdd" v-perm="['sys:position:add']">
                <template #icon><PlusOutlined /></template>
                新建
            </a-button>
            <a-button type="danger" @click="handleDelete()" :disabled="!selectionData.length" v-perm="['sys:position:batchDelete']">
                <template #icon><DeleteOutlined /></template>
                删除
            </a-button>
        </a-space>
    </template>
    <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
            <a-space>
                <a-button type="primary" @click="handleEdit(record.id)" v-perm="['sys:position:update']">
                    <template #icon><EditOutlined /></template>
                    编辑
                </a-button>
                <a-button type="primary" danger @click="handleDelete(record.id)" v-perm="['sys:position:delete']">
                    <template #icon><DeleteOutlined /></template>
                    删除
                </a-button>
            </a-space>
        </template>
    </template>
</BasicTable>

列定义

columns 定义表格列,支持 customRender 函数自定义渲染:

// src/views/system/position/columns.ts

import { h } from 'vue';
import { Tag } from 'ant-design-vue';

export const columns = [
    {
        title: 'ID',
        dataIndex: 'id',
        fixed: 'left',
        width: 50,
    },
    {
        title: '岗位名称',
        dataIndex: 'name',
        width: 100,
    },
    {
        title: '岗位状态',
        dataIndex: 'status',
        width: 100,
        customRender({ record }) {
            return h(
                Tag,
                { color: record.status == 1 ? 'success' : 'error' },
                { default: () => (record.status == 1 ? '正常' : '停用') },
            );
        },
    },
    {
        title: '排序',
        dataIndex: 'sort',
        width: 100,
    },
    {
        title: '创建人',
        dataIndex: 'createUser',
        width: 100,
    },
    {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 180,
    },
    {
        title: '操作',
        fixed: 'right',
        dataIndex: 'action',
        key: 'action',
        width: 200,
    },
];

列配置项

属性 类型 说明
dataIndex string 字段名
title string 列标题
width number 固定宽度
fixed string 固定列:left / right
key string 列唯一标识(操作列需要)
customRender function 自定义渲染函数,接收 { text, record, index, column }
ellipsis boolean 是否溢出省略

customRender 函数中 record 是行数据,text 是当前单元格值。

数据请求

request 属性传入数据请求函数,组件自动管理分页和 loading:

const loadDataTable = async (res: any) => {
    const result = await getPositionList({ ...formParams, ...res });
    return result;  // 返回 { data, count } 结构
};

内部通过 useDataSource Hook 实现:自动传入 pageNo、pageSize 参数,自动设置 total,自动管理 loading 状态。

操作列

操作列通过 bodyCell 插槽实现,使用 v-perm 指令控制权限:

<template #bodyCell="{ column, record }">
    <template v-if="column.key === 'action'">
        <a-space>
            <a-button type="primary" @click="handleEdit(record.id)" v-perm="['sys:position:update']">
                <template #icon><EditOutlined /></template>
                编辑
            </a-button>
            <a-button type="primary" danger @click="handleDelete(record.id)" v-perm="['sys:position:delete']">
                <template #icon><DeleteOutlined /></template>
                删除
            </a-button>
        </a-space>
    </template>
</template>

v-perm 指令接受权限数组,内部通过 usePermission Hook 检查,无权限时自动隐藏按钮。

多选

通过 row-selection 属性启用多选,onChange 回调获取选中行:

const selectionData = ref([]);

function onSelectionChange(selectedRowKeys) {
    selectionData.value = selectedRowKeys;
}

// 批量删除
async function handleDelete(id) {
    Modal.confirm({
        title: '提示',
        content: '确定要删除?',
        onOk: async () => {
            id ? await positionDelete(id) : await positionBatchDelete(selectionData.value);
            message.success('删除成功');
            reloadTable();
        },
    });
}

刷新表格

通过 ref 调用 reload 或 reloadTable 方法:

const tableRef = ref();

// 刷新到第一页
function reloadTable(noRefresh = '') {
    tableRef.value.reload(noRefresh ? {} : { pageNo: 1 });
}

// 操作成功后刷新
const handleAdd = async () => {
    positionId.value = 0;
    await nextTick();
    editVisible.value = true;
};

表格工具栏

BasicTable 内置右侧工具栏,支持:

  • 刷新按钮(redo)
  • 密度切换(small / middle / default)
  • 列设置面板(ColumnSetting)
  • 全屏切换
  • 斑马纹开关

通过 showTableSetting 和 tableSetting 属性控制:

<BasicTable
    :showTableSetting="true"
    :tableSetting="{ redo: true, size: true, setting: true, fullscreen: true, striped: true }"
/>

搜索表单联动

列表页中 BasicForm 和 BasicTable 的典型联动模式:

// src/views/system/position/index.vue

const formParams = reactive({ name: '', status: '' });

const [register, {}] = useForm({
    rowProps: { gutter: [16, 0] },
    colProps: {
        xs: 24,
        sm: 24,
        md: 12,
        lg: 8,
        xl: 6,
    },
    labelCol: { span: 6, offset: 0 },
    schemas,
});

// 表单提交:更新查询参数,刷新表格
function handleSubmit(values: Recordable) {
    for (const key in formParams) {
        formParams[key] = '';
    }
    for (const key in values) {
        formParams[key] = values[key];
    }
    reloadTable();
}

// 表单重置:清空查询参数,刷新表格
function handleReset() {
    for (const key in formParams) {
        formParams[key] = '';
    }
    reloadTable();
}

// 数据请求:合并表单参数和分页参数
const loadDataTable = async (res: any) => {
    const result = await getPositionList({ ...formParams, ...res });
    return result;
};

defineExpose

组件通过 defineExpose 暴露的方法:

方法 说明
reload(opt?) 刷新表格(可指定 pageNo)
restReload() 重置后刷新
getDataSource() 获取当前数据源
setTableData(data) 设置表格数据
updateTableData(index, record) 更新指定行
setColumns(columns) 设置列
setLoading(loading) 设置 loading
redoHeight() 重新计算高度

:::tip 温馨提示 BasicTable 内部自动处理分页参数(pageNo/pageSize),调用方只需提供请求函数。操作列通过 bodyCell 插槽实现,配合 v-perm 指令控制权限,与后端 @permission_required 对应。customRender 函数使用 Vue 的 h() 函数创建虚拟 DOM。 :::

总结

BasicTable 封装了列定义(含 customRender 函数自定义渲染)、数据请求(自动分页和 loading)、操作列(bodyCell 插槽 + v-perm 权限控制)、多选、全屏、密度、列设置等表格常用能力。通过 columns 配置化定义列,request 函数自动管理数据加载,bodyCell 插槽配置操作按钮。