zhanghaijun 1 rok temu
rodzic
commit
fdd433da91

+ 1 - 0
.vscode/settings.json

@@ -49,6 +49,7 @@
   },
   "cSpell.words": [
     "iconfont",
+    "persistedstate",
     "unplugin",
     "VITE",
     "vueuse",

+ 2 - 2
src/api/dict.api.ts

@@ -21,7 +21,7 @@ export class DictService {
   /** 获取所有字典 */
   static dictList = async () => request.get<DictList[]>('/system/dict/all')
   // 分页查询
-  static page = (params: any) => request.post('/system/dict/page', params)
+  static page = (params: any) => request.post('/system/dict/all', params)
   // 详情
   static detail = (dictCode: string) => request.post<Dict>('/system/dict/detail', { dictCode })
   // 添加
@@ -36,7 +36,7 @@ export class DictItemService {
   // 获取字典项列表
   static dictItemList = async (dictCode: string) => request.get<DictItem[]>('/system/dict/item/list', { dictCode })
   // 分页查询
-  static page = (params: any) => request.postPage<DictItem[]>('/system/dict/item/page', params)
+  static page = (params: any) => request.postPage<DictItem[]>('/system/dict/item/list', params)
   // 详情
   static detail = (code: string) => request.post<DictItem>('/system/dict/item/detail', { code })
   // 添加

+ 7 - 41
src/composables/useTable.ts

@@ -3,14 +3,7 @@ import { useWindowSize } from '@vueuse/core'
 import { useTableColumns } from './useTableColumns'
 import type { ColumnOption } from '@/types/component'
 import { TableCache, CacheInvalidationStrategy, type ApiResponse } from '../utils/table/tableCache'
-import {
-  type TableError,
-  defaultResponseAdapter,
-  extractTableData,
-  updatePaginationFromResponse,
-  createSmartDebounce,
-  createErrorHandler
-} from '../utils/table/tableUtils'
+import { type TableError, defaultResponseAdapter, extractTableData, updatePaginationFromResponse, createSmartDebounce, createErrorHandler } from '../utils/table/tableUtils'
 
 // 类型推导工具类型
 type InferApiParams<T> = T extends (params: infer P) => any ? P : never
@@ -88,9 +81,7 @@ export interface UseTableConfig<
   }
 }
 
-export function useTable<TApiFn extends (params: any) => Promise<any>>(
-  config: UseTableConfig<TApiFn>
-) {
+export function useTable<TApiFn extends (params: any) => Promise<any>>(config: UseTableConfig<TApiFn>) {
   return useTableImpl(config)
 }
 
@@ -105,27 +96,13 @@ export function useTable<TApiFn extends (params: any) => Promise<any>>(
  * - 错误处理
  * - 列配置管理
  */
-function useTableImpl<TApiFn extends (params: any) => Promise<any>>(
-  config: UseTableConfig<TApiFn>
-) {
+function useTableImpl<TApiFn extends (params: any) => Promise<any>>(config: UseTableConfig<TApiFn>) {
   type TRecord = InferRecordType<InferApiResponse<TApiFn>>
   type TParams = InferApiParams<TApiFn>
   const {
-    core: {
-      apiFn,
-      apiParams = {} as Partial<TParams>,
-      excludeParams = [],
-      immediate = true,
-      columnsFactory,
-      paginationKey = { current: 'pageNum', size: 'pageSize' }
-    },
+    core: { apiFn, apiParams = {} as Partial<TParams>, excludeParams = [], immediate = true, columnsFactory, paginationKey = { current: 'pageNum', size: 'pageSize' } },
     transform: { dataTransformer, responseAdapter = defaultResponseAdapter } = {},
-    performance: {
-      enableCache = false,
-      cacheTime = 5 * 60 * 1000,
-      debounceTime = 300,
-      maxCacheSize = 50
-    } = {},
+    performance: { enableCache = false, cacheTime = 5 * 60 * 1000, debounceTime = 300, maxCacheSize = 50 } = {},
     hooks: { onSuccess, onError, onCacheHit, resetFormCallback } = {},
     debug: { enableLog = false } = {}
   } = config
@@ -250,10 +227,7 @@ function useTableImpl<TApiFn extends (params: any) => Promise<any>>(
   }
 
   // 获取数据的核心方法
-  const fetchData = async (
-    params?: Partial<TParams>,
-    useCache = enableCache
-  ): Promise<ApiResponse<TRecord>> => {
+  const fetchData = async (params?: Partial<TParams>, useCache = enableCache): Promise<ApiResponse<TRecord>> => {
     // 取消上一个请求
     if (abortController) {
       abortController.abort()
@@ -267,15 +241,7 @@ function useTableImpl<TApiFn extends (params: any) => Promise<any>>(
     error.value = null
 
     try {
-      let requestParams = Object.assign(
-        {},
-        searchParams,
-        {
-          [pageKey]: pagination.current,
-          [sizeKey]: pagination.size
-        },
-        params || {}
-      ) as TParams
+      let requestParams = Object.assign({}, searchParams, { [pageKey]: pagination.current, [sizeKey]: pagination.size }, params || {}) as TParams
 
       // 剔除不需要的参数
       if (excludeParams.length > 0) {

+ 3 - 14
src/utils/table/tableCache.ts

@@ -90,13 +90,7 @@ export class TableCache<T> {
     const tags = new Set<string>()
 
     // 添加搜索条件标签
-    const searchKeys = Object.keys(params).filter(
-      (key) =>
-        !['current', 'size', 'total'].includes(key) &&
-        params[key] !== undefined &&
-        params[key] !== '' &&
-        params[key] !== null
-    )
+    const searchKeys = Object.keys(params).filter((key) => !['current', 'size', 'total'].includes(key) && params[key] !== undefined && params[key] !== '' && params[key] !== null)
 
     if (searchKeys.length > 0) {
       const searchTag = searchKeys.map((key) => `${key}:${String(params[key])}`).join('|')
@@ -123,10 +117,7 @@ export class TableCache<T> {
     let oldestTime = Infinity
 
     for (const [key, item] of this.cache.entries()) {
-      if (
-        item.accessCount < minAccessCount ||
-        (item.accessCount === minAccessCount && item.lastAccessTime < oldestTime)
-      ) {
+      if (item.accessCount < minAccessCount || (item.accessCount === minAccessCount && item.lastAccessTime < oldestTime)) {
         lruKey = key
         minAccessCount = item.accessCount
         oldestTime = item.lastAccessTime
@@ -185,9 +176,7 @@ export class TableCache<T> {
 
     for (const [key, item] of this.cache.entries()) {
       // 检查是否包含任意一个标签
-      const hasMatchingTag = tags.some((tag) =>
-        Array.from(item.tags).some((itemTag) => itemTag.includes(tag))
-      )
+      const hasMatchingTag = tags.some((tag) => Array.from(item.tags).some((itemTag) => itemTag.includes(tag)))
 
       if (hasMatchingTag) {
         this.cache.delete(key)

+ 5 - 22
src/utils/table/tableUtils.ts

@@ -36,10 +36,7 @@ function extractTotal(obj: Record<string, unknown>, records: unknown[], fields:
 }
 
 // 辅助函数:提取分页参数
-function extractPagination(
-  obj: Record<string, unknown>,
-  data?: Record<string, unknown>
-): Pick<ApiResponse<unknown>, 'current' | 'size'> | undefined {
+function extractPagination(obj: Record<string, unknown>, data?: Record<string, unknown>): Pick<ApiResponse<unknown>, 'current' | 'size'> | undefined {
   const result: Partial<Pick<ApiResponse<unknown>, 'current' | 'size'>> = {}
   const sources = [obj, data ?? {}]
 
@@ -85,12 +82,7 @@ export const defaultResponseAdapter = <T>(response: unknown): ApiResponse<T> =>
   }
 
   if (typeof response !== 'object') {
-    console.warn(
-      '[tableUtils] 无法识别的响应格式,支持的格式包括: 数组、包含' +
-        recordFields.join('/') +
-        '字段的对象、嵌套data对象。当前格式:',
-      response
-    )
+    console.warn('[tableUtils] 无法识别的响应格式,支持的格式包括: 数组、包含' + recordFields.join('/') + '字段的对象、嵌套data对象。当前格式:', response)
     return { records: [], total: 0 }
   }
 
@@ -141,10 +133,7 @@ export const extractTableData = <T>(response: ApiResponse<T>): T[] => {
 /**
  * 根据API响应更新分页信息
  */
-export const updatePaginationFromResponse = <T>(
-  pagination: Api.Common.PaginationParams,
-  response: ApiResponse<T>
-): void => {
+export const updatePaginationFromResponse = <T>(pagination: Api.Common.PaginationParams, response: ApiResponse<T>): void => {
   pagination.total = response.total ?? pagination.total ?? 0
 
   if (response.current !== undefined) {
@@ -160,10 +149,7 @@ export const updatePaginationFromResponse = <T>(
 /**
  * 创建智能防抖函数 - 支持取消和立即执行
  */
-export const createSmartDebounce = <T extends (...args: any[]) => Promise<any>>(
-  fn: T,
-  delay: number
-): T & { cancel: () => void; flush: () => Promise<any> } => {
+export const createSmartDebounce = <T extends (...args: any[]) => Promise<any>>(fn: T, delay: number): T & { cancel: () => void; flush: () => Promise<any> } => {
   let timeoutId: NodeJS.Timeout | null = null
   let lastArgs: Parameters<T> | null = null
   let lastResolve: ((value: any) => void) | null = null
@@ -227,10 +213,7 @@ export const createSmartDebounce = <T extends (...args: any[]) => Promise<any>>(
 /**
  * 生成错误处理函数
  */
-export const createErrorHandler = (
-  onError?: (error: TableError) => void,
-  enableLog: boolean = false
-) => {
+export const createErrorHandler = (onError?: (error: TableError) => void, enableLog: boolean = false) => {
   const logger = {
     error: (message: string, ...args: any[]) => {
       if (enableLog) console.error(`[useTable] ${message}`, ...args)

+ 3 - 11
src/views/train/system/dictionary/dict-item-add.vue

@@ -6,24 +6,16 @@
 <script setup lang="tsx">
   import { useCrud } from '@/components/crud'
   import { dictItemSchema } from './dict.schemas'
-  const props = defineProps<{
-    dictId?: string
-  }>()
+  const props = defineProps<{ dictCode?: string }>()
   const [BasicCrud] = useCrud({
     ...dictItemSchema,
     // 查询参数处理
     beforeFetch(params: any) {
-      return {
-        ...params,
-        m_EQ_dictId: props.dictId
-      }
+      return { ...params, dictCode: props.dictCode }
     },
     // 表单提交前处理
     transformFormValues(values: any) {
-      return {
-        ...values,
-        dictId: props.dictId
-      }
+      return { ...values, dictCode: props.dictCode }
     },
     toolbarActions: [],
     dropDownToolbarActions: [],

+ 1 - 1
src/views/train/system/dictionary/dict-item.vue

@@ -1,5 +1,5 @@
 <template>
-  <Dialog> <DictItemIndex :dict-id="record.id" /> </Dialog>
+  <Dialog> <DictItemIndex :dictCode="record.code" /> </Dialog>
 </template>
 <script setup lang="tsx">
   import { useDialog } from '@/components/dialog'

+ 9 - 14
src/views/train/system/dictionary/index.vue

@@ -18,6 +18,15 @@
     dropDownToolbarActions: [],
     // 表格行操作
     tableActions: [
+      {
+        label: dictSchema.editButtonText || '编辑',
+        type: 'default',
+        link: true,
+        icon: 'ant-design:edit-outlined',
+        onClick() {
+          crudApi.openEditDialog()
+        }
+      },
       {
         label: '字典项',
         icon: 'ant-design:setting-outlined',
@@ -32,20 +41,6 @@
           }
         }
       }
-    ],
-    // 表格行操作-下拉菜单
-    dropDownActions: [
-      {
-        label: dictSchema.editButtonText || '编辑',
-        type: 'primary',
-        sort: 10,
-        link: true,
-        icon: 'ant-design:edit-outlined',
-        auth: dictSchema.editAuth,
-        onClick() {
-          crudApi.openEditDialog()
-        }
-      }
     ]
   })
 </script>