mirror of
https://github.com/m-xlsea/ruoyi-plus-soybean.git
synced 2025-09-24 07:49:47 +08:00
refactor(projects): finish refactor useTable and apply
This commit is contained in:
@ -1,226 +0,0 @@
|
||||
import { computed, effectScope, onScopeDispose, reactive, ref, watch } from 'vue';
|
||||
import type { Ref } from 'vue';
|
||||
import type { PaginationProps } from 'naive-ui';
|
||||
import { useBoolean, useTable } from '@sa/hooks';
|
||||
import { useAppStore } from '@/store/modules/app';
|
||||
import { $t } from '@/locales';
|
||||
|
||||
type TableData = NaiveUI.TableData;
|
||||
type GetTableData<A extends NaiveUI.TableApiFn> = NaiveUI.GetTableData<A>;
|
||||
type TableColumn<T> = NaiveUI.TableColumn<T>;
|
||||
|
||||
export function useNaiveTable<A extends NaiveUI.TableApiFn>(config: NaiveUI.NaiveTableConfig<A>) {
|
||||
const scope = effectScope();
|
||||
const appStore = useAppStore();
|
||||
|
||||
const { apiFn, apiParams, immediate } = config;
|
||||
|
||||
const SELECTION_KEY = '__selection__';
|
||||
|
||||
const {
|
||||
loading,
|
||||
empty,
|
||||
data,
|
||||
columns,
|
||||
columnChecks,
|
||||
reloadColumns,
|
||||
getData,
|
||||
searchParams,
|
||||
updateSearchParams,
|
||||
resetSearchParams
|
||||
} = useTable<A, GetTableData<A>, TableColumn<GetTableData<A>>>({
|
||||
apiFn,
|
||||
apiParams,
|
||||
columns: config.columns,
|
||||
transformer: res => {
|
||||
const { records = [], current = 1, size = 10, total = 0 } = res.data || {};
|
||||
|
||||
return {
|
||||
data: records,
|
||||
pageNum: current,
|
||||
pageSize: size,
|
||||
total
|
||||
};
|
||||
},
|
||||
getColumnChecks: cols => {
|
||||
const checks: NaiveUI.TableColumnCheck[] = [];
|
||||
|
||||
cols.forEach(column => {
|
||||
if (isTableColumnHasKey(column)) {
|
||||
checks.push({
|
||||
key: column.key as string,
|
||||
title: column.title as string,
|
||||
checked: true
|
||||
});
|
||||
} else if (column.type === 'selection') {
|
||||
checks.push({
|
||||
key: SELECTION_KEY,
|
||||
title: $t('common.check'),
|
||||
checked: true
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return checks;
|
||||
},
|
||||
getColumns: (cols, checks) => {
|
||||
const columnMap = new Map<string, TableColumn<GetTableData<A>>>();
|
||||
|
||||
cols.forEach(column => {
|
||||
if (isTableColumnHasKey(column)) {
|
||||
columnMap.set(column.key as string, column);
|
||||
} else if (column.type === 'selection') {
|
||||
columnMap.set(SELECTION_KEY, column);
|
||||
}
|
||||
});
|
||||
|
||||
const filteredColumns = checks
|
||||
.filter(item => item.checked)
|
||||
.map(check => columnMap.get(check.key) as TableColumn<GetTableData<A>>);
|
||||
|
||||
return filteredColumns;
|
||||
},
|
||||
onFetched: async transformed => {
|
||||
const { pageNum, pageSize, total } = transformed;
|
||||
|
||||
updatePagination({
|
||||
page: pageNum,
|
||||
pageSize,
|
||||
itemCount: total
|
||||
});
|
||||
},
|
||||
immediate
|
||||
});
|
||||
|
||||
const pagination: PaginationProps = reactive({
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
showSizePicker: true,
|
||||
pageSizes: [10, 15, 20, 25, 30],
|
||||
onUpdatePage: async (page: number) => {
|
||||
pagination.page = page;
|
||||
|
||||
updateSearchParams({
|
||||
current: page,
|
||||
size: pagination.pageSize!
|
||||
});
|
||||
|
||||
getData();
|
||||
},
|
||||
onUpdatePageSize: async (pageSize: number) => {
|
||||
pagination.pageSize = pageSize;
|
||||
pagination.page = 1;
|
||||
|
||||
updateSearchParams({
|
||||
current: pagination.page,
|
||||
size: pageSize
|
||||
});
|
||||
|
||||
getData();
|
||||
}
|
||||
});
|
||||
|
||||
// this is for mobile, if the system does not support mobile, you can use `pagination` directly
|
||||
const mobilePagination = computed(() => {
|
||||
const p: PaginationProps = {
|
||||
...pagination,
|
||||
pageSlot: appStore.isMobile ? 3 : 9
|
||||
};
|
||||
|
||||
return p;
|
||||
});
|
||||
|
||||
function updatePagination(update: Partial<PaginationProps>) {
|
||||
Object.assign(pagination, update);
|
||||
}
|
||||
|
||||
scope.run(() => {
|
||||
watch(
|
||||
() => appStore.locale,
|
||||
() => {
|
||||
reloadColumns();
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
onScopeDispose(() => {
|
||||
scope.stop();
|
||||
});
|
||||
|
||||
return {
|
||||
loading,
|
||||
empty,
|
||||
data,
|
||||
columns,
|
||||
columnChecks,
|
||||
reloadColumns,
|
||||
pagination,
|
||||
mobilePagination,
|
||||
updatePagination,
|
||||
getData,
|
||||
searchParams,
|
||||
updateSearchParams,
|
||||
resetSearchParams
|
||||
};
|
||||
}
|
||||
|
||||
export function useNaiveTableOperate<T extends TableData = TableData>(data: Ref<T[]>, getData: () => Promise<void>) {
|
||||
const { bool: drawerVisible, setTrue: openDrawer, setFalse: closeDrawer } = useBoolean();
|
||||
|
||||
const operateType = ref<NaiveUI.TableOperateType>('add');
|
||||
|
||||
function handleAdd() {
|
||||
operateType.value = 'add';
|
||||
openDrawer();
|
||||
}
|
||||
|
||||
/** the editing row data */
|
||||
const editingData: Ref<T | null> = ref(null);
|
||||
|
||||
function handleEdit(id: number) {
|
||||
operateType.value = 'edit';
|
||||
editingData.value = data.value.find(item => item.id === id) || null;
|
||||
|
||||
openDrawer();
|
||||
}
|
||||
|
||||
const checkedRowKeys = ref<string[]>([]);
|
||||
|
||||
/** the hook after the batch delete operation is completed */
|
||||
async function onBatchDeleted() {
|
||||
window.$message?.success($t('common.deleteSuccess'));
|
||||
|
||||
checkedRowKeys.value = [];
|
||||
|
||||
await getData();
|
||||
}
|
||||
|
||||
/** the hook after the delete operation is completed */
|
||||
async function onDeleted() {
|
||||
window.$message?.success($t('common.deleteSuccess'));
|
||||
|
||||
await getData();
|
||||
}
|
||||
|
||||
return {
|
||||
drawerVisible,
|
||||
operateType,
|
||||
handleAdd,
|
||||
editingData,
|
||||
handleEdit,
|
||||
checkedRowKeys,
|
||||
onBatchDeleted,
|
||||
onDeleted,
|
||||
closeDrawer
|
||||
};
|
||||
}
|
||||
|
||||
export function getNaiveTableIndex(pagination: PaginationProps, index: number) {
|
||||
const { page = 1, pageSize = 10 } = pagination;
|
||||
|
||||
return (page - 1) * pageSize + index + 1;
|
||||
}
|
||||
|
||||
function isTableColumnHasKey<T>(column: TableColumn<T>): column is NaiveUI.TableColumnWithKey<T> {
|
||||
return Boolean((column as NaiveUI.TableColumnWithKey<T>).key);
|
||||
}
|
@ -1,153 +1,146 @@
|
||||
import { computed, effectScope, onScopeDispose, reactive, ref, watch } from 'vue';
|
||||
import type { Ref } from 'vue';
|
||||
import type { DataTableBaseColumn, DataTableExpandColumn, DataTableSelectionColumn, PaginationProps } from 'naive-ui';
|
||||
import type { TableColumnGroup } from 'naive-ui/es/data-table/src/interface';
|
||||
import { useBoolean, useLoading } from '@sa/hooks';
|
||||
import type { PaginationProps } from 'naive-ui';
|
||||
import { useBoolean, useHookTable } from '@sa/hooks';
|
||||
import { useAppStore } from '@/store/modules/app';
|
||||
import { $t } from '@/locales';
|
||||
|
||||
type BaseData = Record<string, unknown>;
|
||||
type TableData = NaiveUI.TableData;
|
||||
type GetTableData<A extends NaiveUI.TableApiFn> = NaiveUI.GetTableData<A>;
|
||||
type TableColumn<T> = NaiveUI.TableColumn<T>;
|
||||
|
||||
type ApiFn = (args: any) => Promise<unknown>;
|
||||
|
||||
export type TableColumn<T extends BaseData = BaseData, CustomColumnKey = never> =
|
||||
| (Omit<TableColumnGroup<T>, 'key'> & { key: keyof T | CustomColumnKey })
|
||||
| (Omit<DataTableBaseColumn<T>, 'key'> & { key: keyof T | CustomColumnKey })
|
||||
| DataTableSelectionColumn<T>
|
||||
| DataTableExpandColumn<T>;
|
||||
|
||||
export type TransformedData<TableData extends BaseData = BaseData> = {
|
||||
data: TableData[];
|
||||
pageNum: number;
|
||||
pageSize: number;
|
||||
total: number;
|
||||
};
|
||||
|
||||
/** transform api response to table data */
|
||||
type Transformer<TableData extends BaseData = BaseData, Response = NonNullable<unknown>> = (
|
||||
response: Response
|
||||
) => TransformedData<TableData>;
|
||||
|
||||
/** table config */
|
||||
export type TableConfig<TableData extends BaseData = BaseData, Fn extends ApiFn = ApiFn, CustomColumnKey = never> = {
|
||||
/** api function to get table data */
|
||||
apiFn: Fn;
|
||||
/** api params */
|
||||
apiParams?: Parameters<Fn>[0];
|
||||
/** transform api response to table data */
|
||||
transformer: Transformer<TableData, Awaited<ReturnType<Fn>>>;
|
||||
/** pagination */
|
||||
pagination?: PaginationProps;
|
||||
/**
|
||||
* callback when pagination changed
|
||||
*
|
||||
* @param pagination
|
||||
*/
|
||||
onPaginationChanged?: (pagination: PaginationProps) => void | Promise<void>;
|
||||
/**
|
||||
* whether to get data immediately
|
||||
*
|
||||
* @default true
|
||||
*/
|
||||
immediate?: boolean;
|
||||
/** columns factory */
|
||||
columns: () => TableColumn<TableData, CustomColumnKey>[];
|
||||
};
|
||||
|
||||
/** filter columns */
|
||||
export type FilteredColumn = {
|
||||
key: string;
|
||||
title: string;
|
||||
checked: boolean;
|
||||
};
|
||||
|
||||
export function useTable<TableData extends BaseData, Fn extends ApiFn, CustomColumnKey = never>(
|
||||
config: TableConfig<TableData, Fn, CustomColumnKey>
|
||||
) {
|
||||
export function useTable<A extends NaiveUI.TableApiFn>(config: NaiveUI.NaiveTableConfig<A>) {
|
||||
const scope = effectScope();
|
||||
const appStore = useAppStore();
|
||||
|
||||
const { loading, startLoading, endLoading } = useLoading();
|
||||
const { bool: empty, setBool: setEmpty } = useBoolean();
|
||||
const { apiFn, apiParams, immediate } = config;
|
||||
|
||||
const { apiFn, apiParams, transformer, onPaginationChanged, immediate = true } = config;
|
||||
const SELECTION_KEY = '__selection__';
|
||||
|
||||
const searchParams: NonNullable<Parameters<Fn>[0]> = reactive({ ...apiParams });
|
||||
const {
|
||||
loading,
|
||||
empty,
|
||||
data,
|
||||
columns,
|
||||
columnChecks,
|
||||
reloadColumns,
|
||||
getData,
|
||||
searchParams,
|
||||
updateSearchParams,
|
||||
resetSearchParams
|
||||
} = useHookTable<A, GetTableData<A>, TableColumn<NaiveUI.TableDataWithIndex<GetTableData<A>>>>({
|
||||
apiFn,
|
||||
apiParams,
|
||||
columns: config.columns,
|
||||
transformer: res => {
|
||||
const { records = [], current = 1, size = 10, total = 0 } = res.data || {};
|
||||
|
||||
const { columns, filteredColumns, reloadColumns } = useTableColumn(config.columns);
|
||||
const recordsWithIndex = records.map((item, index) => {
|
||||
return {
|
||||
...item,
|
||||
index: (current - 1) * size + index + 1
|
||||
};
|
||||
});
|
||||
|
||||
const data: Ref<TableData[]> = ref([]);
|
||||
return {
|
||||
data: recordsWithIndex,
|
||||
pageNum: current,
|
||||
pageSize: size,
|
||||
total
|
||||
};
|
||||
},
|
||||
getColumnChecks: cols => {
|
||||
const checks: NaiveUI.TableColumnCheck[] = [];
|
||||
|
||||
const pagination = reactive({
|
||||
cols.forEach(column => {
|
||||
if (isTableColumnHasKey(column)) {
|
||||
checks.push({
|
||||
key: column.key as string,
|
||||
title: column.title as string,
|
||||
checked: true
|
||||
});
|
||||
} else if (column.type === 'selection') {
|
||||
checks.push({
|
||||
key: SELECTION_KEY,
|
||||
title: $t('common.check'),
|
||||
checked: true
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return checks;
|
||||
},
|
||||
getColumns: (cols, checks) => {
|
||||
const columnMap = new Map<string, TableColumn<GetTableData<A>>>();
|
||||
|
||||
cols.forEach(column => {
|
||||
if (isTableColumnHasKey(column)) {
|
||||
columnMap.set(column.key as string, column);
|
||||
} else if (column.type === 'selection') {
|
||||
columnMap.set(SELECTION_KEY, column);
|
||||
}
|
||||
});
|
||||
|
||||
const filteredColumns = checks
|
||||
.filter(item => item.checked)
|
||||
.map(check => columnMap.get(check.key) as TableColumn<GetTableData<A>>);
|
||||
|
||||
return filteredColumns;
|
||||
},
|
||||
onFetched: async transformed => {
|
||||
const { pageNum, pageSize, total } = transformed;
|
||||
|
||||
updatePagination({
|
||||
page: pageNum,
|
||||
pageSize,
|
||||
itemCount: total
|
||||
});
|
||||
},
|
||||
immediate
|
||||
});
|
||||
|
||||
const pagination: PaginationProps = reactive({
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
showSizePicker: true,
|
||||
pageSizes: [10, 15, 20, 25, 30],
|
||||
// Fix Naive Pagination's outdated API
|
||||
onUpdatePage: async (page: number) => {
|
||||
pagination.page = page;
|
||||
|
||||
await onPaginationChanged?.(pagination);
|
||||
updateSearchParams({
|
||||
current: page,
|
||||
size: pagination.pageSize!
|
||||
});
|
||||
|
||||
getData();
|
||||
},
|
||||
onUpdatePageSize: async (pageSize: number) => {
|
||||
pagination.pageSize = pageSize;
|
||||
pagination.page = 1;
|
||||
|
||||
await onPaginationChanged?.(pagination);
|
||||
},
|
||||
...config.pagination
|
||||
}) as PaginationProps;
|
||||
updateSearchParams({
|
||||
current: pagination.page,
|
||||
size: pageSize
|
||||
});
|
||||
|
||||
getData();
|
||||
}
|
||||
});
|
||||
|
||||
// this is for mobile, if the system does not support mobile, you can use `pagination` directly
|
||||
const mobilePagination = computed(() => {
|
||||
const p: PaginationProps = {
|
||||
...pagination,
|
||||
pageSlot: appStore.isMobile ? 3 : 9
|
||||
};
|
||||
|
||||
return p;
|
||||
});
|
||||
|
||||
function updatePagination(update: Partial<PaginationProps>) {
|
||||
Object.assign(pagination, update);
|
||||
}
|
||||
|
||||
async function getData() {
|
||||
startLoading();
|
||||
|
||||
const formattedParams = formatSearchParams(searchParams);
|
||||
|
||||
const response = await apiFn(formattedParams);
|
||||
|
||||
const { data: tableData, pageNum, pageSize, total } = transformer(response as Awaited<ReturnType<Fn>>);
|
||||
|
||||
data.value = tableData;
|
||||
|
||||
setEmpty(tableData.length === 0);
|
||||
updatePagination({ page: pageNum, pageSize, itemCount: total });
|
||||
endLoading();
|
||||
}
|
||||
|
||||
function formatSearchParams(params: Record<string, unknown>) {
|
||||
const formattedParams: Record<string, unknown> = {};
|
||||
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value !== null && value !== undefined) {
|
||||
formattedParams[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
return formattedParams;
|
||||
}
|
||||
|
||||
/**
|
||||
* update search params
|
||||
*
|
||||
* @param params
|
||||
*/
|
||||
function updateSearchParams(params: Partial<Parameters<Fn>[0]>) {
|
||||
Object.assign(searchParams, params);
|
||||
}
|
||||
|
||||
/** reset search params */
|
||||
function resetSearchParams() {
|
||||
Object.assign(searchParams, apiParams);
|
||||
}
|
||||
|
||||
if (immediate) {
|
||||
getData();
|
||||
}
|
||||
|
||||
scope.run(() => {
|
||||
watch(
|
||||
() => appStore.locale,
|
||||
@ -166,9 +159,10 @@ export function useTable<TableData extends BaseData, Fn extends ApiFn, CustomCol
|
||||
empty,
|
||||
data,
|
||||
columns,
|
||||
filteredColumns,
|
||||
columnChecks,
|
||||
reloadColumns,
|
||||
pagination,
|
||||
mobilePagination,
|
||||
updatePagination,
|
||||
getData,
|
||||
searchParams,
|
||||
@ -177,62 +171,58 @@ export function useTable<TableData extends BaseData, Fn extends ApiFn, CustomCol
|
||||
};
|
||||
}
|
||||
|
||||
function useTableColumn<TableData extends BaseData, CustomColumnKey = never>(
|
||||
factory: () => TableColumn<TableData, CustomColumnKey>[]
|
||||
) {
|
||||
const SELECTION_KEY = '__selection__';
|
||||
export function useTableOperate<T extends TableData = TableData>(data: Ref<T[]>, getData: () => Promise<void>) {
|
||||
const { bool: drawerVisible, setTrue: openDrawer, setFalse: closeDrawer } = useBoolean();
|
||||
|
||||
const allColumns = ref(factory()) as Ref<TableColumn<TableData, CustomColumnKey>[]>;
|
||||
const operateType = ref<NaiveUI.TableOperateType>('add');
|
||||
|
||||
const filteredColumns: Ref<FilteredColumn[]> = ref(getFilteredColumns(factory()));
|
||||
|
||||
const columns = computed(() => getColumns());
|
||||
|
||||
function reloadColumns() {
|
||||
allColumns.value = factory();
|
||||
filteredColumns.value = getFilteredColumns(factory());
|
||||
function handleAdd() {
|
||||
operateType.value = 'add';
|
||||
openDrawer();
|
||||
}
|
||||
|
||||
function getFilteredColumns(aColumns: TableColumn<TableData, CustomColumnKey>[]) {
|
||||
const cols: FilteredColumn[] = [];
|
||||
/** the editing row data */
|
||||
const editingData: Ref<T | null> = ref(null);
|
||||
|
||||
aColumns.forEach(column => {
|
||||
if (column.type === undefined) {
|
||||
cols.push({
|
||||
key: column.key as string,
|
||||
title: column.title as string,
|
||||
checked: true
|
||||
});
|
||||
}
|
||||
function handleEdit(id: T['id']) {
|
||||
operateType.value = 'edit';
|
||||
editingData.value = data.value.find(item => item.id === id) || null;
|
||||
|
||||
if (column.type === 'selection') {
|
||||
cols.push({
|
||||
key: SELECTION_KEY,
|
||||
title: $t('common.check'),
|
||||
checked: true
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return cols;
|
||||
openDrawer();
|
||||
}
|
||||
|
||||
function getColumns() {
|
||||
const cols = filteredColumns.value
|
||||
.filter(column => column.checked)
|
||||
.map(column => {
|
||||
if (column.key === SELECTION_KEY) {
|
||||
return allColumns.value.find(col => col.type === 'selection');
|
||||
}
|
||||
return allColumns.value.find(col => (col as DataTableBaseColumn).key === column.key);
|
||||
});
|
||||
/** the checked row keys of table */
|
||||
const checkedRowKeys = ref<string[]>([]);
|
||||
|
||||
return cols as TableColumn<TableData, CustomColumnKey>[];
|
||||
/** the hook after the batch delete operation is completed */
|
||||
async function onBatchDeleted() {
|
||||
window.$message?.success($t('common.deleteSuccess'));
|
||||
|
||||
checkedRowKeys.value = [];
|
||||
|
||||
await getData();
|
||||
}
|
||||
|
||||
/** the hook after the delete operation is completed */
|
||||
async function onDeleted() {
|
||||
window.$message?.success($t('common.deleteSuccess'));
|
||||
|
||||
await getData();
|
||||
}
|
||||
|
||||
return {
|
||||
columns,
|
||||
reloadColumns,
|
||||
filteredColumns
|
||||
drawerVisible,
|
||||
operateType,
|
||||
handleAdd,
|
||||
editingData,
|
||||
handleEdit,
|
||||
checkedRowKeys,
|
||||
onBatchDeleted,
|
||||
onDeleted,
|
||||
closeDrawer
|
||||
};
|
||||
}
|
||||
|
||||
function isTableColumnHasKey<T>(column: TableColumn<T>): column is NaiveUI.TableColumnWithKey<T> {
|
||||
return Boolean((column as NaiveUI.TableColumnWithKey<T>).key);
|
||||
}
|
||||
|
Reference in New Issue
Block a user