feat(hooks): 完成表格 Hooks 改造

This commit is contained in:
xlsea
2025-07-31 17:08:06 +08:00
parent 01116c9ffa
commit 4699654fc1
15 changed files with 1204 additions and 41 deletions

View File

@ -1,4 +1,4 @@
import { computed, effectScope, onScopeDispose, reactive, shallowRef, watch } from 'vue';
import { computed, effectScope, onScopeDispose, reactive, ref, shallowRef, watch } from 'vue';
import type { Ref } from 'vue';
import type { PaginationProps } from 'naive-ui';
import { useBoolean, useTable } from '@sa/hooks';
@ -224,7 +224,15 @@ export function defaultTransform<ApiData>(
): PaginationData<ApiData> {
const { data, error } = response;
if (!error) {
if (error) {
return {
data: [],
pageNum: 1,
pageSize: 10,
total: 0
};
}
const { rows: records, pageSize: current, pageNum: size, total } = data;
return {
@ -233,16 +241,199 @@ export function defaultTransform<ApiData>(
pageSize: size,
total
};
}
type UseNaiveTreeTableOptions<ResponseData, ApiData> = UseNaiveTableOptions<ResponseData, ApiData, false> & {
keyField: keyof ApiData;
defaultExpandAll?: boolean;
};
export function useNaiveTreeTable<ResponseData, ApiData>(options: UseNaiveTreeTableOptions<ResponseData, ApiData>) {
const scope = effectScope();
const appStore = useAppStore();
const rows: Ref<ApiData[]> = ref([]);
const result = useTable<ResponseData, ApiData, NaiveUI.TableColumn<ApiData>, false>({
...options,
pagination: false,
getColumnChecks: cols => getColumnChecks(cols, options.getColumnVisible),
getColumns,
onFetched: data => {
rows.value = data;
}
});
const { keyField = 'id', defaultExpandAll = false } = options;
const expandedRowKeys = ref<ApiData[keyof ApiData][]>([]);
const { bool: isCollapse, toggle: toggleCollapse } = useBoolean(defaultExpandAll);
/** expand all nodes */
function expandAll() {
toggleCollapse();
expandedRowKeys.value = rows.value.map(item => item[keyField as keyof ApiData]);
}
/** collapse all nodes */
function collapseAll() {
toggleCollapse();
expandedRowKeys.value = [];
}
scope.run(() => {
watch(
() => appStore.locale,
() => {
result.reloadColumns();
}
);
});
onScopeDispose(() => {
scope.stop();
});
return {
...result,
rows,
isCollapse,
expandedRowKeys,
expandAll,
collapseAll
};
}
export function useTreeTableOperate<ApiData>(data: Ref<ApiData[]>, idKey: keyof ApiData, getData: () => Promise<void>) {
const { bool: drawerVisible, setTrue: openDrawer, setFalse: closeDrawer } = useBoolean();
const operateType = shallowRef<NaiveUI.TableOperateType>('add');
function handleAdd() {
operateType.value = 'add';
openDrawer();
}
/** the editing row data */
const editingData = shallowRef<ApiData | null>(null);
function handleEdit(id: ApiData[keyof ApiData]) {
operateType.value = 'edit';
const findItem = data.value.find(item => item[idKey] === id) || null;
editingData.value = jsonClone(findItem);
openDrawer();
}
/** the checked row keys of table */
const checkedRowKeys = shallowRef<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 {
data: [],
pageNum: 1,
pageSize: 10,
total: 0
drawerVisible,
openDrawer,
closeDrawer,
operateType,
handleAdd,
editingData,
handleEdit,
checkedRowKeys,
onBatchDeleted,
onDeleted
};
}
type TreeTableOptions<ApiData> = {
/** id field name */
idField?: keyof ApiData;
/** parent id field name */
parentIdField?: keyof ApiData;
/** children field name */
childrenField?: keyof ApiData;
/** filter function */
filterFn?: (node: ApiData) => boolean;
};
export function treeTransform<ApiData>(
response: FlatResponseData<any, ApiData[]>,
options: TreeTableOptions<ApiData>
): ApiData[] {
const { data, error } = response;
if (error || !data.length) {
return [];
}
const { idField = 'id', parentIdField = 'parentId', childrenField = 'children', filterFn = () => true } = options;
// 使用 Map 替代普通对象,提高性能
const childrenMap = new Map<ApiData[keyof ApiData], ApiData[]>();
const nodeMap = new Map<ApiData[keyof ApiData], ApiData>();
const tree: ApiData[] = [];
// 第一遍遍历:构建节点映射
for (const item of data) {
const id = item[idField as keyof ApiData];
const parentId = item[parentIdField as keyof ApiData];
nodeMap.set(id, item);
if (!childrenMap.has(parentId)) {
childrenMap.set(parentId, []);
}
// 应用过滤函数
if (filterFn(item)) {
childrenMap.get(parentId)!.push(item);
}
}
// 第二遍遍历:找出根节点
for (const item of data) {
const parentId = item[parentIdField as keyof ApiData];
if (!nodeMap.has(parentId) && filterFn(item)) {
tree.push(item);
}
}
// 递归构建树形结构
const buildTree = (node: ApiData) => {
const id = node[idField as keyof ApiData];
const children = childrenMap.get(id);
if (children?.length) {
// 使用类型断言确保类型安全
(node as any)[childrenField] = children;
for (const child of children) {
buildTree(child);
}
} else {
// 如果没有子节点,设置为 undefined
(node as any)[childrenField] = undefined;
}
};
// 从根节点开始构建树
for (const root of tree) {
buildTree(root);
}
return tree;
}
function getColumnChecks<Column extends NaiveUI.TableColumn<any>>(
cols: Column[],
getColumnVisible?: (column: Column) => boolean

View File

@ -243,6 +243,9 @@ const local: App.I18n.Schema = {
'social-callback': 'Social Callback',
monitor_cache: 'Cache Monitor',
'user-center': 'User Center',
demo: 'Demo',
demo_demo: 'Demo Table',
demo_tree: 'Demo Tree',
exception: 'Exception',
exception_403: '403',
exception_404: '404',

View File

@ -240,6 +240,9 @@ const local: App.I18n.Schema = {
'social-callback': '单点登录回调',
monitor_cache: '缓存监控',
'user-center': '个人中心',
demo: '测试',
demo_demo: '测试单表',
demo_tree: '测试树表',
exception: '异常页',
exception_403: '403',
exception_404: '404',

View File

@ -22,6 +22,8 @@ export const views: Record<LastLevelRouteKey, RouteComponent | (() => Promise<Ro
login: () => import("@/views/_builtin/login/index.vue"),
"social-callback": () => import("@/views/_builtin/social-callback/index.vue"),
"user-center": () => import("@/views/_builtin/user-center/index.vue"),
demo_demo: () => import("@/views/demo/demo/index.vue"),
demo_tree: () => import("@/views/demo/tree/index.vue"),
home: () => import("@/views/home/index.vue"),
monitor_cache: () => import("@/views/monitor/cache/index.vue"),
};

View File

@ -39,6 +39,35 @@ export const generatedRoutes: GeneratedRoute[] = [
hideInMenu: true
}
},
{
name: 'demo',
path: '/demo',
component: 'layout.base',
meta: {
title: 'demo',
i18nKey: 'route.demo'
},
children: [
{
name: 'demo_demo',
path: '/demo/demo',
component: 'view.demo_demo',
meta: {
title: 'demo_demo',
i18nKey: 'route.demo_demo'
}
},
{
name: 'demo_tree',
path: '/demo/tree',
component: 'view.demo_tree',
meta: {
title: 'demo_tree',
i18nKey: 'route.demo_tree'
}
}
]
},
{
name: 'home',
path: '/home',

View File

@ -170,6 +170,9 @@ const routeMap: RouteMap = {
"403": "/403",
"404": "/404",
"500": "/500",
"demo": "/demo",
"demo_demo": "/demo/demo",
"demo_tree": "/demo/tree",
"home": "/home",
"iframe-page": "/iframe-page/:url",
"login": "/login/:module(pwd-login|code-login|register|reset-pwd|bind-wechat)?",

View File

@ -25,6 +25,32 @@ export const request = createFlatRequest(
refreshTokenPromise: null
} as RequestInstanceState,
transform(response: AxiosResponse<App.Service.Response<any>>) {
if (import.meta.env.VITE_APP_ENCRYPT === 'Y') {
// 加密后的 AES 秘钥
const keyStr = response.headers[encryptHeader];
// 加密
if (keyStr && keyStr !== '') {
const data = String(response.data);
// 请求体 AES 解密
const base64Str = decrypt(keyStr);
// base64 解码 得到请求头的 AES 秘钥
const aesKey = decryptBase64(base64Str.toString());
// aesKey 解码 data
const decryptData = decryptWithAes(data, aesKey);
// 将结果 (得到的是 JSON 字符串) 转为 JSON
response.data = JSON.parse(decryptData);
}
}
// 二进制数据则直接返回
if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
return response.data;
}
if (response.data.rows) {
return response.data;
}
return response.data.data;
},
async onRequest(config) {
@ -131,35 +157,6 @@ export const request = createFlatRequest(
return null;
},
transformBackendResponse(response) {
if (import.meta.env.VITE_APP_ENCRYPT === 'Y') {
// 加密后的 AES 秘钥
const keyStr = response.headers[encryptHeader];
// 加密
if (keyStr && keyStr !== '') {
const data = String(response.data);
// 请求体 AES 解密
const base64Str = decrypt(keyStr);
// base64 解码 得到请求头的 AES 秘钥
const aesKey = decryptBase64(base64Str.toString());
// aesKey 解码 data
const decryptData = decryptWithAes(data, aesKey);
// 将结果 (得到的是 JSON 字符串) 转为 JSON
response.data = JSON.parse(decryptData);
}
}
// 二进制数据则直接返回
if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
return response.data;
}
if (response.data.rows) {
return response.data;
}
return response.data.data;
},
onError(error) {
// when the request is fail, you can show error message

View File

@ -26,15 +26,25 @@ declare module 'vue' {
FullScreen: typeof import('./../components/common/full-screen.vue')['default']
IconAntDesignEnterOutlined: typeof import('~icons/ant-design/enter-outlined')['default']
IconAntDesignReloadOutlined: typeof import('~icons/ant-design/reload-outlined')['default']
IconAntDesignSettingOutlined: typeof import('~icons/ant-design/setting-outlined')['default']
IconGridiconsFullscreen: typeof import('~icons/gridicons/fullscreen')['default']
IconGridiconsFullscreenExit: typeof import('~icons/gridicons/fullscreen-exit')['default']
IconIcRoundRefresh: typeof import('~icons/ic/round-refresh')['default']
IconIcRoundSearch: typeof import('~icons/ic/round-search')['default']
IconLocalBanner: typeof import('~icons/local/banner')['default']
IconLocalLogo: typeof import('~icons/local/logo')['default']
'IconMaterialSymbols:add': typeof import('~icons/material-symbols/add')['default']
'IconMaterialSymbols:deleteOutline': typeof import('~icons/material-symbols/delete-outline')['default']
'IconMaterialSymbols:downloadRounded': typeof import('~icons/material-symbols/download-rounded')['default']
'IconMaterialSymbols:refreshRounded': typeof import('~icons/material-symbols/refresh-rounded')['default']
'IconMdi:github': typeof import('~icons/mdi/github')['default']
IconMdiArrowDownThin: typeof import('~icons/mdi/arrow-down-thin')['default']
IconMdiArrowUpThin: typeof import('~icons/mdi/arrow-up-thin')['default']
IconMdiDrag: typeof import('~icons/mdi/drag')['default']
IconMdiKeyboardEsc: typeof import('~icons/mdi/keyboard-esc')['default']
IconMdiKeyboardReturn: typeof import('~icons/mdi/keyboard-return')['default']
'IconQuill:collapse': typeof import('~icons/quill/collapse')['default']
'IconQuill:expand': typeof import('~icons/quill/expand')['default']
'IconSimpleIcons:gitee': typeof import('~icons/simple-icons/gitee')['default']
IconUilSearch: typeof import('~icons/uil/search')['default']
JsonPreview: typeof import('./../components/custom/json-preview.vue')['default']
@ -53,7 +63,10 @@ declare module 'vue' {
NButton: typeof import('naive-ui')['NButton']
NCard: typeof import('naive-ui')['NCard']
NCheckbox: typeof import('naive-ui')['NCheckbox']
NCollapse: typeof import('naive-ui')['NCollapse']
NCollapseItem: typeof import('naive-ui')['NCollapseItem']
NColorPicker: typeof import('naive-ui')['NColorPicker']
NDataTable: typeof import('naive-ui')['NDataTable']
NDialogProvider: typeof import('naive-ui')['NDialogProvider']
NDivider: typeof import('naive-ui')['NDivider']
NDrawer: typeof import('naive-ui')['NDrawer']
@ -63,6 +76,7 @@ declare module 'vue' {
NEmpty: typeof import('naive-ui')['NEmpty']
NForm: typeof import('naive-ui')['NForm']
NFormItem: typeof import('naive-ui')['NFormItem']
NFormItemGi: typeof import('naive-ui')['NFormItemGi']
NGi: typeof import('naive-ui')['NGi']
NGrid: typeof import('naive-ui')['NGrid']
NInput: typeof import('naive-ui')['NInput']
@ -75,6 +89,7 @@ declare module 'vue' {
NMessageProvider: typeof import('naive-ui')['NMessageProvider']
NModal: typeof import('naive-ui')['NModal']
NNotificationProvider: typeof import('naive-ui')['NNotificationProvider']
NP: typeof import('naive-ui')['NP']
NPopconfirm: typeof import('naive-ui')['NPopconfirm']
NPopover: typeof import('naive-ui')['NPopover']
NScrollbar: typeof import('naive-ui')['NScrollbar']
@ -86,8 +101,12 @@ declare module 'vue' {
NTab: typeof import('naive-ui')['NTab']
NTabs: typeof import('naive-ui')['NTabs']
NTag: typeof import('naive-ui')['NTag']
NText: typeof import('naive-ui')['NText']
NThing: typeof import('naive-ui')['NThing']
NTooltip: typeof import('naive-ui')['NTooltip']
NTreeSelect: typeof import('naive-ui')['NTreeSelect']
NUpload: typeof import('naive-ui')['NUpload']
NUploadDragger: typeof import('naive-ui')['NUploadDragger']
NWatermark: typeof import('naive-ui')['NWatermark']
OssUpload: typeof import('./../components/custom/oss-upload.vue')['default']
PinToggler: typeof import('./../components/common/pin-toggler.vue')['default']

View File

@ -24,6 +24,9 @@ declare module "@elegant-router/types" {
"403": "/403";
"404": "/404";
"500": "/500";
"demo": "/demo";
"demo_demo": "/demo/demo";
"demo_tree": "/demo/tree";
"home": "/home";
"iframe-page": "/iframe-page/:url";
"login": "/login/:module(pwd-login|code-login|register|reset-pwd|bind-wechat)?";
@ -69,6 +72,7 @@ declare module "@elegant-router/types" {
| "403"
| "404"
| "500"
| "demo"
| "home"
| "iframe-page"
| "login"
@ -99,6 +103,8 @@ declare module "@elegant-router/types" {
| "login"
| "social-callback"
| "user-center"
| "demo_demo"
| "demo_tree"
| "home"
| "monitor_cache"
>;

View File

@ -0,0 +1,204 @@
<script setup lang="tsx">
import { reactive } from 'vue';
import { NDivider } from 'naive-ui';
import { fetchBatchDeleteDemo, fetchGetDemoList } from '@/service/api/demo';
import { useAppStore } from '@/store/modules/app';
import { useAuth } from '@/hooks/business/auth';
import { useDownload } from '@/hooks/business/download';
import { defaultTransform, useNaivePaginatedTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import ButtonIcon from '@/components/custom/button-icon.vue';
import DemoOperateDrawer from './modules/demo-operate-drawer.vue';
import DemoSearch from './modules/demo-search.vue';
defineOptions({
name: 'DemoList'
});
const appStore = useAppStore();
const { download } = useDownload();
const { hasAuth } = useAuth();
const searchParams: Api.Demo.DemoSearchParams = reactive({
pageNum: 1,
pageSize: 10,
deptId: null,
userId: null,
orderNum: null,
testKey: null,
value: null,
params: {}
});
const { columns, columnChecks, data, getData, getDataByPage, loading, mobilePagination } = useNaivePaginatedTable({
api: () => fetchGetDemoList(searchParams),
transform: response => defaultTransform(response),
onPaginationParamsChange: params => {
searchParams.pageSize = params.page;
searchParams.pageNum = params.pageSize;
},
columns: () => [
{
type: 'selection',
align: 'center',
width: 48
},
{
key: 'id',
title: '主键',
align: 'center',
minWidth: 120
},
{
key: 'deptId',
title: '部门 ID',
align: 'center',
minWidth: 120
},
{
key: 'userId',
title: '用户 ID',
align: 'center',
minWidth: 120
},
{
key: 'orderNum',
title: '排序号',
align: 'center',
minWidth: 120
},
{
key: 'testKey',
title: 'key 键',
align: 'center',
minWidth: 120
},
{
key: 'value',
title: '值',
align: 'center',
minWidth: 120
},
{
key: 'operate',
title: $t('common.operate'),
align: 'center',
width: 130,
render: row => {
const divider = () => {
if (!hasAuth('demo:demo:edit') || !hasAuth('demo:demo:remove')) {
return null;
}
return <NDivider vertical />;
};
const editBtn = () => {
if (!hasAuth('demo:demo:edit')) {
return null;
}
return (
<ButtonIcon
text
type="primary"
icon="material-symbols:drive-file-rename-outline-outline"
tooltipContent={$t('common.edit')}
onClick={() => edit(row.id!)}
/>
);
};
const deleteBtn = () => {
if (!hasAuth('demo:demo:remove')) {
return null;
}
return (
<ButtonIcon
text
type="error"
icon="material-symbols:delete-outline"
tooltipContent={$t('common.delete')}
popconfirmContent={$t('common.confirmDelete')}
onPositiveClick={() => handleDelete(row.id!)}
/>
);
};
return (
<div class="flex-center gap-8px">
{editBtn()}
{divider()}
{deleteBtn()}
</div>
);
}
}
]
});
const { drawerVisible, operateType, editingData, handleAdd, handleEdit, checkedRowKeys, onBatchDeleted, onDeleted } =
useTableOperate(data, 'id', getData);
async function handleBatchDelete() {
// request
const { error } = await fetchBatchDeleteDemo(checkedRowKeys.value);
if (error) return;
onBatchDeleted();
}
async function handleDelete(id: CommonType.IdType) {
// request
const { error } = await fetchBatchDeleteDemo([id]);
if (error) return;
onDeleted();
}
async function edit(id: CommonType.IdType) {
handleEdit(id);
}
async function handleExport() {
download('/demo/demo/export', searchParams, `测试单表_${new Date().getTime()}.xlsx`);
}
</script>
<template>
<div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
<DemoSearch v-model:model="searchParams" @search="getDataByPage" />
<NCard title="测试单表列表" :bordered="false" size="small" class="card-wrapper sm:flex-1-hidden">
<template #header-extra>
<TableHeaderOperation
v-model:columns="columnChecks"
:disabled-delete="checkedRowKeys.length === 0"
:loading="loading"
:show-add="hasAuth('demo:demo:add')"
:show-delete="hasAuth('demo:demo:remove')"
:show-export="hasAuth('demo:demo:export')"
@add="handleAdd"
@delete="handleBatchDelete"
@export="handleExport"
@refresh="getData"
/>
</template>
<DataTable
v-model:checked-row-keys="checkedRowKeys"
:columns="columns"
:data="data"
:flex-height="!appStore.isMobile"
:scroll-x="962"
:loading="loading"
remote
:row-key="row => row.id"
:pagination="mobilePagination"
class="sm:h-full"
/>
<DemoOperateDrawer
v-model:visible="drawerVisible"
:operate-type="operateType"
:row-data="editingData"
@submitted="getData"
/>
</NCard>
</div>
</template>
<style scoped></style>

View File

@ -0,0 +1,144 @@
<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { fetchCreateDemo, fetchUpdateDemo } from '@/service/api/demo/demo';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
defineOptions({
name: 'DemoOperateDrawer'
});
interface Props {
/** the type of operation */
operateType: NaiveUI.TableOperateType;
/** the edit row data */
rowData?: Api.Demo.Demo | null;
}
const props = defineProps<Props>();
interface Emits {
(e: 'submitted'): void;
}
const emit = defineEmits<Emits>();
const visible = defineModel<boolean>('visible', {
default: false
});
const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();
const title = computed(() => {
const titles: Record<NaiveUI.TableOperateType, string> = {
add: '新增测试单表',
edit: '编辑测试单表'
};
return titles[props.operateType];
});
type Model = Api.Demo.DemoOperateParams;
const model: Model = reactive(createDefaultModel());
function createDefaultModel(): Model {
return {
deptId: null,
userId: null,
orderNum: null,
testKey: '',
value: '',
remark: ''
};
}
type RuleKey = Extract<keyof Model, 'id' | 'deptId' | 'userId' | 'orderNum' | 'testKey' | 'value'>;
const rules: Record<RuleKey, App.Global.FormRule> = {
id: createRequiredRule('主键不能为空'),
deptId: createRequiredRule('部门不能为空'),
userId: createRequiredRule('用户不能为空'),
orderNum: createRequiredRule('排序号不能为空'),
testKey: createRequiredRule('key 键不能为空'),
value: createRequiredRule('值不能为空')
};
function handleUpdateModelWhenEdit() {
if (props.operateType === 'add') {
Object.assign(model, createDefaultModel());
return;
}
if (props.operateType === 'edit' && props.rowData) {
Object.assign(model, props.rowData);
}
}
function closeDrawer() {
visible.value = false;
}
async function handleSubmit() {
await validate();
// request
if (props.operateType === 'add') {
const { deptId, userId, orderNum, testKey, value } = model;
const { error } = await fetchCreateDemo({ deptId, userId, orderNum, testKey, value });
if (error) return;
}
if (props.operateType === 'edit') {
const { id, deptId, userId, orderNum, testKey, value } = model;
const { error } = await fetchUpdateDemo({ id, deptId, userId, orderNum, testKey, value });
if (error) return;
}
window.$message?.success($t('common.updateSuccess'));
closeDrawer();
emit('submitted');
}
watch(visible, () => {
if (visible.value) {
handleUpdateModelWhenEdit();
restoreValidation();
}
});
</script>
<template>
<NDrawer v-model:show="visible" :title="title" display-directive="show" :width="800" class="max-w-90%">
<NDrawerContent :title="title" :native-scrollbar="false" closable>
<NForm ref="formRef" :model="model" :rules="rules">
<NFormItem label="部门" path="deptId">
<DeptTreeSelect v-model:value="model.deptId" placeholder="请选择部门" />
</NFormItem>
<NFormItem label="用户" path="userId">
<UserSelect v-model:value="model.userId" placeholder="请选择用户" />
</NFormItem>
<NFormItem label="排序号" path="orderNum">
<NInputNumber v-model:value="model.orderNum" placeholder="请输入排序号" />
</NFormItem>
<NFormItem label="key 键" path="testKey">
<NInput v-model:value="model.testKey" placeholder="请输入 key 键" />
</NFormItem>
<NFormItem label="值" path="value">
<OssUpload v-model:value="model.value as string" upload-type="image" placeholder="请输入值" />
</NFormItem>
<NFormItem label="备注" path="remark">
<NInput v-model:value="model.remark" type="textarea" placeholder="请输入备注" />
</NFormItem>
</NForm>
<template #footer>
<NSpace :size="16">
<NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
<NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
</NSpace>
</template>
</NDrawerContent>
</NDrawer>
</template>
<style scoped></style>

View File

@ -0,0 +1,84 @@
<script setup lang="ts">
import { useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
defineOptions({
name: 'DemoSearch'
});
interface Emits {
(e: 'search'): void;
}
const emit = defineEmits<Emits>();
const { formRef, validate, restoreValidation } = useNaiveForm();
const model = defineModel<Api.Demo.DemoSearchParams>('model', { required: true });
function resetModel() {
model.value = {
pageNum: 1,
pageSize: 10,
deptId: null,
userId: null,
orderNum: null,
testKey: null,
value: null,
params: {}
};
}
async function reset() {
await restoreValidation();
resetModel();
}
async function search() {
await validate();
emit('search');
}
</script>
<template>
<NCard :bordered="false" size="small" class="card-wrapper">
<NCollapse>
<NCollapseItem :title="$t('common.search')" name="user-search">
<NForm ref="formRef" :model="model" label-placement="left" :label-width="80">
<NGrid responsive="screen" item-responsive>
<NFormItemGi span="24 s:12 m:6" label="部门" path="deptId" class="pr-24px">
<DeptTreeSelect v-model:value="model.deptId" placeholder="请选择部门" />
</NFormItemGi>
<NFormItemGi span="24 s:12 m:6" label="用户" path="userId" class="pr-24px">
<UserSelect v-model:value="model.userId" placeholder="请选择用户" />
</NFormItemGi>
<NFormItemGi span="24 s:12 m:6" label="key 键" path="testKey" class="pr-24px">
<NInput v-model:value="model.testKey" placeholder="请输入 key 键" />
</NFormItemGi>
<NFormItemGi span="24 s:12 m:6" label="值" path="value" class="pr-24px">
<NInput v-model:value="model.value" placeholder="请输入值" />
</NFormItemGi>
<NFormItemGi :show-feedback="false" span="24" class="pr-24px">
<NSpace class="w-full" justify="end">
<NButton @click="reset">
<template #icon>
<icon-ic-round-refresh class="text-icon" />
</template>
{{ $t('common.reset') }}
</NButton>
<NButton type="primary" ghost @click="search">
<template #icon>
<icon-ic-round-search class="text-icon" />
</template>
{{ $t('common.search') }}
</NButton>
</NSpace>
</NFormItemGi>
</NGrid>
</NForm>
</NCollapseItem>
</NCollapse>
</NCard>
</template>
<style scoped></style>

View File

@ -0,0 +1,224 @@
<script setup lang="tsx">
import { reactive } from 'vue';
import { NDivider } from 'naive-ui';
import { jsonClone } from '@sa/utils';
import { fetchBatchDeleteTree, fetchGetTreeList } from '@/service/api/demo/tree';
import { useAppStore } from '@/store/modules/app';
import { useAuth } from '@/hooks/business/auth';
import { treeTransform, useNaiveTreeTable, useTableOperate } from '@/hooks/common/table';
import { useDownload } from '@/hooks/business/download';
import { $t } from '@/locales';
import ButtonIcon from '@/components/custom/button-icon.vue';
import TreeOperateDrawer from './modules/tree-operate-drawer.vue';
import TreeSearch from './modules/tree-search.vue';
defineOptions({
name: 'TreeList'
});
const appStore = useAppStore();
const { download } = useDownload();
const { hasAuth } = useAuth();
const searchParams: Api.Demo.TreeSearchParams = reactive({
pageNum: 1,
pageSize: 10,
parentId: null,
deptId: null,
userId: null,
treeName: null,
params: {}
});
const { columns, columnChecks, data, rows, getData, loading, expandedRowKeys, isCollapse, expandAll, collapseAll } =
useNaiveTreeTable({
keyField: 'id',
api: fetchGetTreeList,
transform: response => treeTransform(response, { idField: 'id' }),
columns: () => [
{
type: 'selection',
align: 'center',
width: 48
},
{
key: 'id',
title: '主键',
align: 'center',
minWidth: 120
},
{
key: 'parentId',
title: '父 ID',
align: 'center',
minWidth: 120
},
{
key: 'deptId',
title: '部门 ID',
align: 'center',
minWidth: 120
},
{
key: 'userId',
title: '用户 ID',
align: 'center',
minWidth: 120
},
{
key: 'treeName',
title: '值',
align: 'center',
minWidth: 120
},
{
key: 'operate',
title: $t('common.operate'),
align: 'center',
width: 130,
render: row => {
const addBtn = () => {
return (
<ButtonIcon
text
type="primary"
icon="material-symbols:add-2-rounded"
tooltipContent={$t('common.add')}
onClick={() => addInRow(row)}
/>
);
};
const editBtn = () => {
return (
<ButtonIcon
text
type="primary"
icon="material-symbols:drive-file-rename-outline-outline"
tooltipContent={$t('common.edit')}
onClick={() => edit(row.id)}
/>
);
};
const deleteBtn = () => {
return (
<ButtonIcon
text
type="error"
icon="material-symbols:delete-outline"
tooltipContent={$t('common.delete')}
popconfirmContent={$t('common.confirmDelete')}
onPositiveClick={() => handleDelete(row.id)}
/>
);
};
const buttons = [];
if (hasAuth('demo:tree:add')) buttons.push(addBtn());
if (hasAuth('demo:tree:edit')) buttons.push(editBtn());
if (hasAuth('demo:tree:remove')) buttons.push(deleteBtn());
return (
<div class="flex-center gap-8px">
{buttons.map((btn, index) => (
<>
{index !== 0 && <NDivider vertical />}
{btn}
</>
))}
</div>
);
}
}
]
});
const { drawerVisible, operateType, editingData, handleAdd, handleEdit, checkedRowKeys, onBatchDeleted, onDeleted } =
useTableOperate(rows, 'id', getData);
async function handleBatchDelete() {
// request
const { error } = await fetchBatchDeleteTree(checkedRowKeys.value);
if (error) return;
onBatchDeleted();
}
async function handleDelete(id: CommonType.IdType) {
// request
const { error } = await fetchBatchDeleteTree([id]);
if (error) return;
onDeleted();
}
async function edit(id: CommonType.IdType) {
handleEdit(id);
}
function addInRow(row: Api.Demo.Tree) {
editingData.value = jsonClone(row);
handleAdd();
}
function handleExport() {
download('/demo/tree/export', searchParams, `demo_tree_#[[${new Date().getTime()}]]#.xlsx`);
}
</script>
<template>
<div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
<TreeSearch v-model:model="searchParams" :tree-list="data" @search="getData" />
<NCard title="测试树列表" :bordered="false" size="small" class="card-wrapper sm:flex-1-hidden">
<template #header-extra>
<TableHeaderOperation
v-model:columns="columnChecks"
:disabled-delete="checkedRowKeys.length === 0"
:loading="loading"
:show-add="hasAuth('demo:tree:add')"
:show-delete="hasAuth('demo:tree:remove')"
:show-export="false"
@add="handleAdd"
@delete="handleBatchDelete"
@export="handleExport"
@refresh="getData"
>
<template #prefix>
<NButton v-if="!isCollapse" :disabled="!data.length" size="small" @click="expandAll">
<template #icon>
<icon-quill:expand />
</template>
全部展开
</NButton>
<NButton v-if="isCollapse" :disabled="!data.length" size="small" @click="collapseAll">
<template #icon>
<icon-quill:collapse />
</template>
全部收起
</NButton>
</template>
</TableHeaderOperation>
</template>
<DataTable
v-model:checked-row-keys="checkedRowKeys"
v-model:expanded-row-keys="expandedRowKeys"
:columns="columns"
:data="data"
:flex-height="!appStore.isMobile"
:scroll-x="962"
:loading="loading"
remote
:row-key="row => row.id"
class="sm:h-full"
/>
<TreeOperateDrawer
v-model:visible="drawerVisible"
:operate-type="operateType"
:row-data="editingData"
:tree-list="data"
@submitted="getData"
/>
</NCard>
</div>
</template>
<style scoped></style>

View File

@ -0,0 +1,156 @@
<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { fetchCreateTree, fetchUpdateTree } from '@/service/api/demo/tree';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
defineOptions({
name: 'TreeOperateDrawer'
});
interface Props {
/** the type of operation */
operateType: NaiveUI.TableOperateType;
/** the edit row data */
rowData?: Api.Demo.Tree | null;
/** the tree data */
treeList?: Api.Demo.Tree[] | null;
}
const props = defineProps<Props>();
interface Emits {
(e: 'submitted'): void;
}
const emit = defineEmits<Emits>();
const visible = defineModel<boolean>('visible', {
default: false
});
const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();
const title = computed(() => {
const titles: Record<NaiveUI.TableOperateType, string> = {
add: '新增测试树',
edit: '编辑测试树'
};
return titles[props.operateType];
});
type Model = Api.Demo.TreeOperateParams;
const model: Model = reactive(createDefaultModel());
function createDefaultModel(): Model {
return {
parentId: null,
deptId: null,
userId: null,
treeName: ''
};
}
type RuleKey = Extract<keyof Model, 'id' | 'parentId' | 'deptId' | 'userId' | 'treeName'>;
const rules: Record<RuleKey, App.Global.FormRule> = {
id: createRequiredRule('主键不能为空'),
parentId: createRequiredRule('父 ID 不能为空'),
deptId: createRequiredRule('部门不能为空'),
userId: createRequiredRule('用户不能为空'),
treeName: createRequiredRule('值不能为空')
};
function handleUpdateModelWhenEdit() {
if (props.operateType === 'add') {
Object.assign(model, createDefaultModel());
model.parentId = props.rowData?.id || 0;
return;
}
if (props.operateType === 'edit' && props.rowData) {
Object.assign(model, props.rowData);
}
}
function closeDrawer() {
visible.value = false;
}
async function handleSubmit() {
await validate();
// request
if (props.operateType === 'add') {
const { parentId, deptId, userId, treeName } = model;
const { error } = await fetchCreateTree({ parentId, deptId, userId, treeName });
if (error) return;
}
if (props.operateType === 'edit') {
const { id, parentId, deptId, userId, treeName } = model;
const { error } = await fetchUpdateTree({ id, parentId, deptId, userId, treeName });
if (error) return;
}
window.$message?.success($t('common.updateSuccess'));
closeDrawer();
emit('submitted');
}
watch(visible, () => {
if (visible.value) {
handleUpdateModelWhenEdit();
restoreValidation();
}
});
const treeOptions = computed(() => {
return [
{
id: 0,
treeName: '顶级节点',
children: props.treeList!
}
];
});
</script>
<template>
<NDrawer v-model:show="visible" :title="title" display-directive="show" :width="800" class="max-w-90%">
<NDrawerContent :title="title" :native-scrollbar="false" closable>
<NForm ref="formRef" :model="model" :rules="rules">
<NFormItem label="父 ID" path="parentId">
<NTreeSelect
v-model:value="model.parentId"
filterable
class="h-full"
key-field="id"
label-field="treeName"
:options="treeOptions"
:default-expanded-keys="[0]"
/>
</NFormItem>
<NFormItem label="部门" path="deptId">
<DeptTreeSelect v-model:value="model.deptId" placeholder="请选择部门" />
</NFormItem>
<NFormItem label="用户" path="userId">
<UserSelect v-model:value="model.userId" placeholder="请选择用户" />
</NFormItem>
<NFormItem label="值" path="treeName">
<NInput v-model:value="model.treeName" placeholder="请输入值" />
</NFormItem>
</NForm>
<template #footer>
<NSpace :size="16">
<NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
<NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
</NSpace>
</template>
</NDrawerContent>
</NDrawer>
</template>
<style scoped></style>

View File

@ -0,0 +1,98 @@
<script setup lang="ts">
import { useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
defineOptions({
name: 'TreeSearch'
});
interface Props {
/** the tree list */
treeList?: Api.Demo.Tree[] | null;
}
defineProps<Props>();
interface Emits {
(e: 'search'): void;
}
const emit = defineEmits<Emits>();
const { formRef, validate, restoreValidation } = useNaiveForm();
const model = defineModel<Api.Demo.TreeSearchParams>('model', { required: true });
function resetModel() {
model.value = {
pageNum: 1,
pageSize: 10,
parentId: null,
deptId: null,
userId: null,
treeName: null,
params: {}
};
}
async function reset() {
await restoreValidation();
resetModel();
}
async function search() {
await validate();
emit('search');
}
</script>
<template>
<NCard :bordered="false" size="small" class="card-wrapper">
<NCollapse>
<NCollapseItem :title="$t('common.search')" name="user-search">
<NForm ref="formRef" :model="model" label-placement="left" :label-width="80">
<NGrid responsive="screen" item-responsive>
<NFormItemGi span="24 s:12 m:6" label="父 ID" path="parentId" class="pr-24px">
<NTreeSelect
v-model:value="model.parentId"
filterable
class="h-full"
key-field="id"
label-field="treeName"
:options="treeList!"
:default-expanded-keys="[0]"
/>
</NFormItemGi>
<NFormItemGi span="24 s:12 m:6" label="部门" path="deptId" class="pr-24px">
<DeptTreeSelect v-model:value="model.deptId" placeholder="请选择部门" />
</NFormItemGi>
<NFormItemGi span="24 s:12 m:6" label="用户" path="userId" class="pr-24px">
<UserSelect v-model:value="model.userId" placeholder="请选择用户" />
</NFormItemGi>
<NFormItemGi span="24 s:12 m:6" label="值" path="treeName" class="pr-24px">
<NInput v-model:value="model.treeName" placeholder="请输入值" />
</NFormItemGi>
<NFormItemGi :show-feedback="false" span="24" class="pr-24px">
<NSpace class="w-full" justify="end">
<NButton @click="reset">
<template #icon>
<icon-ic-round-refresh class="text-icon" />
</template>
{{ $t('common.reset') }}
</NButton>
<NButton type="primary" ghost @click="search">
<template #icon>
<icon-ic-round-search class="text-icon" />
</template>
{{ $t('common.search') }}
</NButton>
</NSpace>
</NFormItemGi>
</NGrid>
</NForm>
</NCollapseItem>
</NCollapse>
</NCard>
</template>
<style scoped></style>