基于vue3.0和element-plus的组件库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.3 KiB

import { toReactive } from "@vueuse/core";
import { reactive, ref, shallowRef, toRaw, watchEffect } from "vue";
import * as Element from "../element";
import { useI18n } from "vue3-i18n";
import { PageResponse } from "../http";
import { clearAndAssign, deepCopy } from "../util/objectUtil";
const { showMessage } = Element;
export interface TableColumn {
code: string;
name?: string;
i18n?: string;
type?: string;
width?: string | number;
fixed?: boolean | "left" | "right";
align?: "left" | "center" | "right";
slot?: boolean;
dict?: string;
timestamp?: boolean;
filesize?: boolean;
[others: string]: any;
}
export interface TableData {
rows: PageResponse<any>;
example: Record<string, any>;
}
interface Options {
query: (example: any) => Promise<PageResponse<any> | Record<string, any>[] | undefined>;
initialPage?: number;
initialPageSize?: number;
initExample?: Record<string, any>;
disableAutoQuery?: boolean;
deep?: boolean;
}
export function useListTable(options: Options) {
const { t } = useI18n();
const { initialPage, initialPageSize, initExample, deep } = options;
type Row = Record<string, any>;
type Rows = Row[] | PageResponse<Row>;
const empty = <T>() => [] as T[];
const rows = deep ? ref<Rows>(empty()) : shallowRef<Rows>(empty());
const setRows = (resp?: Rows) => {
if (resp == null) {
rows.value = empty();
} else {
rows.value = resp;
if (Array.isArray(resp) || resp.total == null) {
for (const key in pageParams) {
delete example[key];
}
}
}
};
const pageParams = {
page: initialPage || 1,
size: initialPageSize || 10,
};
const defaultExample = () => ({
...pageParams,
...initExample,
});
const example = reactive<any>(defaultExample());
const setExample = (params: Record<string, any>) => {
clearAndAssign(example, { ...defaultExample(), ...params });
};
const query = async () => {
try {
const resp = await options.query(deepCopy(toRaw(example)));
setRows(resp);
} catch (error) {
console.error(error);
showMessage("error", t("common.errors.listTableQueryError"));
}
};
if (!options.disableAutoQuery) {
watchEffect(query);
}
return {
rows: toReactive(rows),
example,
setRows,
setExample,
query,
};
}