### Development Server Start Command Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/configuration.md Starts the development server using npm. The default port is 5173, and the --host flag makes it accessible on the network. ```bash npm run dev # Starts at http://localhost:5173 (default Vite port) # With --host flag: accessible on network IP ``` -------------------------------- ### Global Store Usage Example Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/stores.md Illustrates how to import and use multiple stores (e.g., `useUserStore`, `useAppStore`) within a Vue component's script setup. Shows direct state access and method calls. ```typescript ``` -------------------------------- ### Get List Example Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Demonstrates how to retrieve a paginated list of records with custom filters. Ensure the API supports the specified query parameters. ```typescript const { getList } = getBaseApi({ baseUrl: '/user' }) const response = await getList({ page: 1, size: 20, status: 1 }) // response.data → { records: [...], total: 100 } ``` -------------------------------- ### Get Detail Example Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Shows how to fetch details for a single record using its unique identifier. The ID must correspond to an existing record. ```typescript const { getDetail } = getBaseApi({ baseUrl: '/user' }) const user = await getDetail({ id: '123' }) ``` -------------------------------- ### Get User Info API Request Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Example of how to make a GET request to fetch the current user's information. Requires a valid token in the headers. ```typescript const userInfo = await http.get('/user/getUserInfo') // { id: '1', nickname: 'Admin User', roles: ['admin'], ... } ``` -------------------------------- ### Login Flow Example Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Illustrates the login process and how the token is automatically used for subsequent requests. Includes fetching user info, routes, and dictionaries. ```typescript // 1. Login const loginRes = await http.post('/user/login', { username: 'admin', password: '123456' }) const token = loginRes.data.token // 2. Token automatically injected in subsequent requests // 3. Fetch user info const userInfo = await http.get('/user/getUserInfo') // 4. Fetch routes const routes = await http.get('/user/getUserRoutes') // 5. Fetch dictionaries const dicts = await http.get('/system/dict/getDictData') ``` -------------------------------- ### Get User Routes API Request Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Example of how to make a GET request to fetch dynamic routes for the current user. Returns a hierarchical route structure based on user permissions. ```typescript const routes = await http.get('/user/getUserRoutes') // Returns hierarchical route structure with permissions applied ``` -------------------------------- ### Menu Badge Store Example Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/stores.md Demonstrates how to use the `useMenuBadgeStore` to set and remove badges for menu items. Shows direct method calls. ```typescript const badgeStore = useMenuBadgeStore() badgeStore.setBadge('/messages', 5) // Show "5" badge on Messages menu badgeStore.removeBadge('/messages') // Clear badge ``` -------------------------------- ### API Response Example Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/types.md Demonstrates how to use the ApiRes type when fetching user information. Checks the success flag before accessing the data. ```typescript const response: ApiRes = await http.get('/user/getUserInfo') if (response.success) { console.log(response.data.nickname) } ``` -------------------------------- ### CRUD Operations Example Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Demonstrates common Create, Read, Update, and Delete (CRUD) operations using a base API configuration for user resources. ```typescript const api = getBaseApi({ baseUrl: '/users' }) // List const list = await api.getList({ page: 1, size: 10 }) // Detail const detail = await api.getDetail({ id: '1' }) // Create const created = await api.add({ name: 'John' }) // Update const updated = await api.update({ id: '1', name: 'Jane' }) // Delete await api.delete({ ids: ['1', '2', '3'] }) ``` -------------------------------- ### Table Data Loading Example Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Shows how to fetch paginated data for a table, including handling the response and updating UI elements like records and total count. ```typescript const response = await http.get('/users/getList', { page: 1, size: 20, status: 1 }) if (response.success) { const { records, total } = response.data // Update table with records // Set pagination total to total } ``` -------------------------------- ### Basic useTable Hook Usage Example Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/hooks.md Demonstrates how to initialize and use the useTable hook with API endpoints for listing and deleting data. Includes configuration for row key and immediate data fetching. ```typescript import { useTable } from '@/hooks' const { loading, tableData, pagination, selectedKeys, search, refresh, onDelete, onBatchDelete } = useTable({ listAPI: (p) => getUserList(p), deleteAPI: (ids) => deleteUser({ ids }), rowKey: 'id', immediate: true }) // In template: // ``` -------------------------------- ### Add Record Example Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Illustrates creating a new record by sending the necessary data in the request body. The response will contain the newly created object. ```typescript const { add } = getBaseApi({ baseUrl: '/user' }) const newUser = await add({ name: 'John', email: 'john@example.com' }) ``` -------------------------------- ### Update Record Example Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Demonstrates updating an existing record by providing its ID and the fields to modify. The response contains the updated object. ```typescript const { update } = getBaseApi({ baseUrl: '/user' }) const updated = await update({ id: '123', name: 'Jane', email: 'jane@example.com' }) ``` -------------------------------- ### User Login API Request Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Example of how to make a POST request to the user login endpoint. Requires username and password in the request body. ```typescript import http from '@/utils/http' const response = await http.post('/user/login', { username: 'admin', password: '123456' }) // response.data.token → 'eyJhbGciOiJIUzI1NiIs...' ``` -------------------------------- ### Delete Records Example Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Shows how to delete one or more records by providing an array of their IDs. The response indicates whether the deletion was successful. ```typescript const { delete: deleteUser } = getBaseApi({ baseUrl: '/user' }) const success = await deleteUser({ ids: ['123', '456'] }) ``` -------------------------------- ### Paginated Response Example Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/types.md Shows how to destructure the data from a paginated API response, accessing both the records and the total count. ```typescript const response: ApiRes> = await http.get('/user/getList') const { records, total } = response.data ``` -------------------------------- ### GET /getList Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Retrieve a paginated list of records. Supports custom filters for specific API implementations. ```APIDOC ## GET {baseUrl}/getList ### Description Retrieve paginated list. Supports custom filters. ### Method GET ### Endpoint {baseUrl}/getList ### Parameters #### Query Parameters - **page** (number) - Optional - Page number (1-based), defaults to 1. - **size** (number) - Optional - Items per page, defaults to 10. - **...rest** (any) - Optional - Custom filters (API-specific). ### Response #### Success Response (200) - **records** (T[]) - Array of records. - **total** (number) - Total number of records. ### Request Example ```typescript const { getList } = getBaseApi({ baseUrl: '/user' }) const response = await getList({ page: 1, size: 20, status: 1 }) // response.data → { records: [...], total: 100 } ``` ``` -------------------------------- ### GET /user/getUserInfo Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Retrieves detailed information about the currently authenticated user, including roles and permissions. ```APIDOC ## GET /user/getUserInfo ### Description Fetch current user information. Requires authentication. ### Method GET ### Endpoint /user/getUserInfo ### Response #### Success Response (200) - **id** (string) - User identifier - **nickname** (string) - User's display name - **avatar** (string) - Avatar image URL - **roles** (string[]) - Role identifiers (e.g., ['admin', 'user']) - **permissions** (string[]) - Permission strings (e.g., ['user:list', 'user:add']) #### Response Example ```json { "id": "1", "nickname": "Admin User", "avatar": "/path/to/avatar.jpg", "roles": ["admin"], "permissions": ["read:data", "write:data"] } ``` ### Status Codes - `code: 200` — Success - `code: 401` — Not authenticated ### Authentication Requires valid token in headers ``` -------------------------------- ### GET /user/getUserRoutes Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Fetches the dynamic route structure for the current user, based on their assigned roles and permissions. ```APIDOC ## GET /user/getUserRoutes ### Description Fetch dynamic routes for the current user. Returns a hierarchical route structure that can be dynamically added to the application's router. ### Method GET ### Endpoint /user/getUserRoutes ### Response #### Success Response (200) - Returns an array of `UserRouteItem` objects representing the user's accessible routes. **Route Item Structure:** ```typescript { id: string parentId: string path: string component: string // Vue component path icon: string title: string redirect: string keepAlive: boolean breadcrumb: boolean showInTabs: boolean hidden: boolean type: 1 | 2 | 3 // 1=directory, 2=menu, 3=button status: 0 | 1 // 0=disabled, 1=enabled sort: number roles: string[] permission: string alwaysShow: boolean activeMenu: string children: UserRouteItem[] affix: boolean } ``` ### Status Codes - `code: 200` — Success - `code: 401` — Not authenticated ### Authentication Requires valid token ``` -------------------------------- ### GET /getDetail Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Retrieve the details of a single record using its identifier. ```APIDOC ## GET {baseUrl}/getDetail ### Description Retrieve single record details. ### Method GET ### Endpoint {baseUrl}/getDetail ### Parameters #### Query Parameters - **id** (string) - Required - Record identifier. ### Response #### Success Response (200) - (T) - Single object of type `T`. ### Request Example ```typescript const { getDetail } = getBaseApi({ baseUrl: '/user' }) const user = await getDetail({ id: '123' }) ``` ``` -------------------------------- ### Get a time-based greeting Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/utilities.md Retrieves a localized greeting based on the current hour of the day. Useful for user interfaces. ```typescript export function goodTimeText(): string ``` ```typescript goodTimeText() // Returns based on current hour: // < 9: '早上好' // 9-11: '上午好' // 12-13: '中午好' // 14-19: '下午好' // >= 20: '晚上好' ``` -------------------------------- ### User Logout API Request Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Example of how to make a POST request to the user logout endpoint. This endpoint does not require a request body. ```typescript await http.post('/user/logout') ``` -------------------------------- ### Global Directive Registration Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/directives.md Register the 'hasPerm' and 'hasRole' directives globally using a Vue plugin. This setup ensures directives are available throughout the application. ```typescript // src/directives/index.ts export default { install(Vue: App) { Vue.directive('hasPerm', hasPerm) Vue.directive('hasRole', hasRole) } } // src/main.ts - Registered at app startup app.use(directives) ``` -------------------------------- ### Build Commands for Development and Production Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/configuration.md Provides commands for different build types: development with type checking, optimized production build, type checking only, and previewing the production build. ```bash # Development build with type checking npm run build-tsc # Runs vue-tsc --noEmit && vite build # Production build npm run build # Optimized, minified output # Type checking only npm run typecheck # vue-tsc --noEmit # Preview production build npm run preview # Serves dist/ on http://localhost:5050 ``` -------------------------------- ### Using useTheme Hook Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/hooks.md Demonstrates how to import and use the useTheme hook to manage theme and color settings. ```typescript import { useTheme } from '@/hooks' const { isDark, toggleTheme, setThemeColor } = useTheme() const onColorChange = (color: string) => { setThemeColor(color) // e.g., '#377DFF' } ``` -------------------------------- ### Dynamic Form Usage Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/README.md Demonstrates how to use the `gi-form` component in a template, binding it to a form data model and passing the column configuration for rendering. ```html ``` -------------------------------- ### Using useChart Hook Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/hooks.md Demonstrates importing and using the useChart hook to initialize and configure an ECharts instance. ```typescript import { useChart } from '@/hooks' import { ref } from 'vue' const { chartRef, setOption } = useChart() setOption({ xAxis: { type: 'category' }, yAxis: { type: 'value' }, series: [{ data: [1, 2, 3], type: 'line' }] }) ``` -------------------------------- ### Using useDevice Hook Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/hooks.md Shows how to import and use the useDevice hook to conditionally render UI based on device type. ```typescript import { useDevice } from '@/hooks' const { isMobile } = useDevice() // Show mobile-optimized UI if (isMobile.value) { // render mobile layout } ``` -------------------------------- ### useTheme Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/hooks.md Theme and color management hook. Manages theme state with localStorage persistence. Uses Arco Design color generation to create theme color scales. ```APIDOC ## useTheme ### Description Theme and color management hook. Manages theme state with localStorage persistence. Uses Arco Design color generation to create theme color scales. ### Signature ```typescript export function useTheme(): { isDark: Ref theme: ComputedRef<'dark' | 'light'> toggleTheme: () => void setThemeColor: (color: string) => void initThemeColor: () => void } ``` ### Returns #### isDark - Type: `Ref` - Description: Is dark mode enabled #### theme - Type: `ComputedRef<'dark' | 'light'>` - Description: Current theme name #### toggleTheme - Type: `() => void` - Description: Toggle between dark/light #### setThemeColor - Type: `(color: string) => void` - Description: Set primary theme color (hex) #### initThemeColor - Type: `() => void` - Description: Initialize theme color from store ### Example ```typescript import { useTheme } from '@/hooks' const { isDark, toggleTheme, setThemeColor } = useTheme() const onColorChange = (color: string) => { setThemeColor(color) // e.g., '#377DFF' } ``` ``` -------------------------------- ### useTabsStore Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/stores.md Manages the state of opened tabs, allowing for adding, updating, and removing tabs. ```APIDOC ## useTabsStore Manages the state of opened tabs. ### Methods #### addTab Adds or updates a tab. - **Parameters** - `tab` (TabItem) - Required - The tab item to add or update. #### removeTab Closes a tab by its route path. - **Parameters** - `path` (string) - Required - The route path of the tab to close. #### removeAllTabs Closes all tabs except for those that are pinned. ``` -------------------------------- ### useMenuBadgeStore Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/stores.md Manages menu badge counts and notification states for different menu items. ```APIDOC ## useMenuBadgeStore Manages menu badge and notification state. ### Methods #### setBadge Sets the badge count for a specific menu item. - **Parameters** - `path` (string) - Required - The menu path to set the badge for. - `count` (number) - Required - The badge count to display. #### removeBadge Clears the badge for a specific menu item. - **Parameters** - `path` (string) - Required - The menu path to clear the badge for. ``` -------------------------------- ### POST /user/login Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Authenticates a user with provided credentials. Returns a token upon successful login. ```APIDOC ## POST /user/login ### Description User login endpoint. Authenticates a user with provided credentials and returns an authorization token. ### Method POST ### Endpoint /user/login ### Parameters #### Request Body - **username** (string) - Yes - Login username - **password** (string) - Yes - Login password ### Request Example ```json { "username": "admin", "password": "123456" } ``` ### Response #### Success Response (200) - **token** (string) - Authorization token for subsequent requests. #### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiIs..." } ``` ### Status Codes - `code: 200` — Login successful - `code: 401` — Invalid credentials ``` -------------------------------- ### POST /add Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Create a new record. The request body structure is specific to the API implementation. ```APIDOC ## POST {baseUrl}/add ### Description Create new record. ### Method POST ### Endpoint {baseUrl}/add ### Request Body Custom per endpoint (extends `AddParams`) ### Response #### Success Response (201 or 200) - (T) - Created object (type `T`). ### Request Example ```typescript const { add } = getBaseApi({ baseUrl: '/user' }) const newUser = await add({ name: 'John', email: 'john@example.com' }) ``` ``` -------------------------------- ### UserRouteItem Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/types.md Dynamic route configuration from backend. Defines properties for menu items, routing, and permissions. ```APIDOC ## UserRouteItem ### Description Dynamic route configuration from backend. Defines properties for menu items, routing, and permissions. ### Type Definition ```typescript export interface UserRouteItem { id: string parentId: string path: string component: string icon: string title: string redirect: string keepAlive: boolean breadcrumb: boolean showInTabs: boolean hidden: boolean type: 1 | 2 | 3 status: 0 | 1 sort: number roles: string[] permission: string alwaysShow: boolean activeMenu: string children: UserRouteItem[] affix: boolean } ``` ### Fields - **id** (string) - Route unique identifier - **parentId** (string) - Parent route ID for hierarchies - **path** (string) - Route path (e.g., '/users/list') - **component** (string) - Vue component file path - **icon** (string) - Menu icon identifier - **title** (string) - Display name in menu - **redirect** (string) - Redirect target path - **keepAlive** (boolean) - Cache component in keep-alive - **breadcrumb** (boolean) - Show in breadcrumb navigation - **showInTabs** (boolean) - Show in tab bar - **hidden** (boolean) - Hide from menu - **type** (1 | 2 | 3) - 1=directory, 2=menu, 3=button - **status** (0 | 1) - 0=disabled, 1=enabled - **sort** (number) - Sort order (ascending) - **roles** (string[]) - Allowed roles - **permission** (string) - Required permission code - **alwaysShow** (boolean) - Always show menu (even with one child) - **activeMenu** (string) - Active menu when on this route - **children** (UserRouteItem[]) - Child routes - **affix** (boolean) - Pin tab (don't close) ``` -------------------------------- ### Fetch User Data with Loading State Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/README.md Use this hook to fetch user information and manage the loading state. It automatically runs the fetch operation upon initialization. ```typescript const { loading, data, run } = useRequest( () => getUserInfo(), { immediate: true } ) ``` -------------------------------- ### Application SettingConfig Interface Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/types.md Defines the structure for application configuration settings, including theme, layout, tab styles, and menu behavior. These settings are typically stored in localStorage. ```typescript declare namespace App { interface SettingConfig { themeColor: string layout: 'left' | 'mix' | 'top' | 'columns' tabStyle: 'card' | 'card-gutter' | 'rounded' | 'custom1' | 'custom2' isTabVisible: boolean transitionName: 'zoom-fade' | 'slide-dynamic-origin' | 'fade-slide' | 'fade' | 'fade-bottom' | 'fade-scale' isTransitionEnabled: boolean isMenuCollapsed: boolean isMenuAccordion: boolean isMenuDark: boolean } } ``` -------------------------------- ### Login Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/types.md Login API response data. Contains the authentication token. ```APIDOC ## Login ### Description Login API response data. Contains the authentication token. ### Type Definition ```typescript export interface Login { token: string } ``` ### Fields - **token** (string) - Authentication token (JWT-like) ``` -------------------------------- ### formatFileSize Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/utilities.md Formats a byte size into a human-readable string. ```APIDOC ## formatFileSize ### Description Format byte size to human-readable format. ### Parameters #### Path Parameters - **size** (number) - Required - Size in bytes ### Returns `string` — Formatted size (e.g., '1.5MB') ### Example ```typescript formatFileSize(1024) // '1KB' formatFileSize(1024 * 1024) // '1MB' formatFileSize(1024 * 1024 * 1024) // '1GB' ``` ### Signature ```typescript export function formatFileSize(size: number): string ``` ``` -------------------------------- ### Theme Management with Hooks Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/README.md Manage application themes, including dark mode toggling, primary color setting, and checking the current theme state. This hook provides a centralized way to control visual styles. ```typescript import { useTheme } from '@/hooks' const { toggleTheme, setThemeColor, isDark } = useTheme() // Switch dark mode toggleTheme() // Set primary color setThemeColor('#FF0000') // Check current theme console.log(isDark.value) ``` -------------------------------- ### Define Menu Badge Store Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/stores.md Defines the Pinia store for managing menu badge and notification states. It holds a map of badge counts by menu path. ```typescript export const useMenuBadgeStore = defineStore('menuBadge', storeSetup) ``` -------------------------------- ### Mock.js Integration with Vite Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/configuration.md Configures vite-plugin-mock to integrate Mock.js into the Vite build process. Specify the directory for mock files and enable the plugin. ```typescript // vite-plugin-mock configuration import { viteMockServe } from 'vite-plugin-mock' export default { plugins: [ viteMockServe({ mockDir: './src/mock', enable: true }) ] } ``` -------------------------------- ### UserInfo Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/types.md Current authenticated user information. Includes user ID, nickname, avatar, roles, and permissions. ```APIDOC ## UserInfo ### Description Current authenticated user information. Includes user ID, nickname, avatar, roles, and permissions. ### Type Definition ```typescript export interface UserInfo { id: string nickname: string avatar: string roles: string[] permissions: string[] } ``` ### Fields - **id** (string) - User unique identifier - **nickname** (string) - User's display name - **avatar** (string) - Avatar image URL - **roles** (string[]) - Role codes (e.g., ['admin', 'user']) - **permissions** (string[]) - Permission codes (e.g., ['user:list', 'user:add']) ``` -------------------------------- ### useChart Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/hooks.md ECharts integration hook. Provides lifecycle management for ECharts instances, including auto-resize handling. ```APIDOC ## useChart ### Description ECharts integration hook. Provides lifecycle management for ECharts instances, including auto-resize handling. ### Signature ```typescript export function useChart(): { chartRef: Ref chartInstance: Ref getOption: () => any setOption: (option: any) => void resize: () => void dispose: () => void } ``` ### Returns #### chartRef - Type: `Ref` - Description: Reference to the chart container element. #### chartInstance - Type: `Ref` - Description: The ECharts instance. #### getOption - Type: `() => any` - Description: Gets the current ECharts option. #### setOption - Type: `(option: any) => void` - Description: Sets the ECharts option. #### resize - Type: `() => void` - Description: Resizes the chart. #### dispose - Type: `() => void` - Description: Disposes the chart instance. ### Example ```typescript import { useChart } from '@/hooks' import { ref } from 'vue' const { chartRef, setOption } = useChart() setOption({ xAxis: { type: 'category' }, yAxis: { type: 'value' }, series: [{ data: [1, 2, 3], type: 'line' }] }) ``` ``` -------------------------------- ### useDevice Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/hooks.md Device detection hook. Detects whether the current device is mobile or desktop. ```APIDOC ## useDevice ### Description Device detection hook. Detects whether the current device is mobile or desktop. ### Signature ```typescript export function useDevice(): { isMobile: ComputedRef isDesktop: ComputedRef } ``` ### Returns #### isMobile - Type: `ComputedRef` - Description: Is mobile device #### isDesktop - Type: `ComputedRef` - Description: Is desktop device ### Example ```typescript import { useDevice } from '@/hooks' const { isMobile } = useDevice() // Show mobile-optimized UI if (isMobile.value) { // render mobile layout } ``` ``` -------------------------------- ### Set Badge Method Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/stores.md Sets or updates the badge count for a specific menu item identified by its path. Requires the path and the count. ```typescript setBadge(path: string, count: number): void ``` -------------------------------- ### useBreakpoint Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/hooks.md Provides responsive breakpoint detection for Vue 3 applications. It returns the current active breakpoint, allowing for dynamic UI adjustments based on screen size. ```APIDOC ## useBreakpoint ### Description Responsive breakpoint detection hook. Returns the current active breakpoint. ### Returns - **breakpoint** (ComputedRef<`'xs'` | `'sm'` | `'md'` | `'lg'` | `'xl'` | `'xxl'`>) - Current active breakpoint ### Breakpoints - **xs**: <576px - **sm**: ≥576px - **md**: ≥768px - **lg**: ≥992px - **xl**: ≥1200px - **xxl**: ≥1600px ### Example ```typescript import { useBreakpoint } from '@/hooks' const { breakpoint } = useBreakpoint() const columnCount = computed(() => { if (['xs', 'sm'].includes(breakpoint.value)) return 1 if (breakpoint.value === 'md') return 2 return 3 }) ``` ``` -------------------------------- ### Dynamic Form Configuration Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/README.md Defines the structure for a dynamic form, specifying input types, labels, fields, and validation rules. This configuration is used with the `gi-form` component for rendering. ```typescript const columns: FormColumnItem[] = [ { type: 'input', label: 'Name', field: 'name', required: true, rules: [{ required: true, message: 'Required' }] }, { type: 'select', label: 'Status', field: 'status', props: { options: statusOptions } } ] ``` -------------------------------- ### setToken Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/utilities.md Stores the authentication token in localStorage. ```APIDOC ## setToken ### Description Store authentication token in localStorage. ### Method ```typescript const setToken = (token: string): void ``` ### Parameters #### Path Parameters - **token** (string) - Required - Authentication token value ``` -------------------------------- ### Define Tabs Store Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/stores.md Defines the Pinia store for managing multi-tab functionality. It includes state properties for open tabs. ```typescript export const useTabsStore = defineStore('tabs', storeSetup) ``` -------------------------------- ### Format file size to human-readable string Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/utilities.md Converts a byte size into a more readable format like KB, MB, or GB. Provide the size in bytes as input. ```typescript export function formatFileSize(size: number): string ``` ```typescript formatFileSize(1024) // '1KB' formatFileSize(1024 * 1024) // '1MB' formatFileSize(1024 * 1024 * 1024) // '1GB' ``` -------------------------------- ### goodTimeText Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/utilities.md Retrieves a time-based greeting string. ```APIDOC ## goodTimeText ### Description Get time-based greeting. ### Returns `string` — Greeting (e.g., '早上好', '下午好') ### Example ```typescript goodTimeText() // Returns based on current hour: // < 9: '早上好' // 9-11: '上午好' // 12-13: '中午好' // 14-19: '下午好' // >= 20: '晚上好' ``` ### Signature ```typescript export function goodTimeText(): string ``` ``` -------------------------------- ### useLoading Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/hooks.md Manages loading states within Vue 3 applications. This hook provides reactive control over a loading boolean, including functions to set and toggle the state. ```APIDOC ## useLoading ### Description Loading state management hook. Manages a reactive loading state with functions to set and toggle. ### Parameters - **initValue** (boolean) - Optional - Default: `false` - Initial loading state ### Returns - **loading** (Ref) - Reactive loading state - **setLoading** (function) - Set loading state to specific value - **toggle** (function) - Toggle loading state ### Example ```typescript import { useLoading } from '@/hooks' const { loading, setLoading, toggle } = useLoading() const fetchData = async () => { setLoading(true) try { await api.getData() } finally { setLoading(false) } } ``` ``` -------------------------------- ### Check for All Specified Permissions Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/utilities.md Ensures that the current user possesses all the permissions specified in the provided array. Use this when a user must have multiple capabilities to perform an action. ```typescript export function hasPermAnd(permissions: string[]): boolean ``` -------------------------------- ### hasPermAnd Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/utilities.md Checks if the user has ALL of the specified permissions. ```APIDOC ## hasPermAnd ### Description Check if user has ALL specified permissions. ### Method ```typescript export function hasPermAnd(permissions: string[]): boolean ``` ### Parameters #### Path Parameters - **permissions** (string[]) - Required - Permission identifier array ### Returns `boolean` — True if user has all permissions ``` -------------------------------- ### Handling API Errors with Try-Catch Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/README.md Illustrates error handling for API requests using a try-catch block. It's assumed that HTTP interceptors already display user-facing error messages, so the catch block focuses on logging. ```typescript // HTTP interceptor catches errors and rejects promise try { const data = await http.get('/api/users') } catch (error) { // Error already shown via Message/Notification console.error(error) } ``` -------------------------------- ### hexToRgb Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/utilities.md Converts a hexadecimal color string to an RGB string representation. ```APIDOC ## hexToRgb ### Description Convert hexadecimal color to RGB. ### Parameters #### Path Parameters - **hex** (string) - Required - Hex color (#optional, supports shorthand) ### Returns `string` — RGB format (e.g., '255, 0, 0') ### Example ```typescript hexToRgb('#FF0000') // '255, 0, 0' hexToRgb('FF0000') // '255, 0, 0' hexToRgb('#F00') // '255, 0, 0' ``` ### Signature ```typescript export function hexToRgb(hex: string): string ``` ``` -------------------------------- ### Handling Successful API Responses Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/README.md Demonstrates how to process successful API responses by checking the 'success' flag and accessing the 'data' field. Assumes HTTP interceptors handle actual network errors. ```typescript const res = await http.get('/api/users') if (res.success) { console.log(res.data) // Use data directly } ``` -------------------------------- ### Check for Any Specified Permissions Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/utilities.md Verifies if the current user has at least one of the permissions listed in the provided array. This is useful for scenarios where multiple actions are permissible. ```typescript if (hasPermOr(['user:edit', 'user:delete'])) { // User can edit OR delete } ``` -------------------------------- ### Permission Checks for Buttons Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/directives.md Conditionally render buttons based on user permissions. Use the 'v-hasPerm' directive with an array of required permissions. ```vue ``` -------------------------------- ### useTable Options Interface Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/hooks.md Defines the configuration options for the useTable hook. This includes data transformation, callbacks, API endpoints, and selection behavior. ```typescript interface Options { formatResult?: (data: T[]) => U[] // Transform API response onSuccess?: () => void // Success callback immediate?: boolean // Auto-fetch on mount (default: true) rowKey?: keyof T // Unique row identifier (default: 'id') crossPageSelect?: boolean // Keep selections across page changes listAPI: (params: { page: number, size: number }) => Promise>> deleteAPI?: (ids: string[]) => Promise> } ``` -------------------------------- ### useTable Hook Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/hooks.md The useTable hook provides a complete set of functionalities for managing table data. It supports pagination, row selection, filtering, and CRUD operations, making it easy to implement dynamic tables. ```APIDOC ## useTable Hook ### Description Complete table management hook with pagination, selection, filtering, and CRUD operations. ### Signature ```typescript export function useTable(options: Options): { loading: Ref tableData: Ref getTableData: () => Promise search: () => void pagination: object selectedKeys: Ref<(string | number)[]> select: (rowKeys: (string | number)[]) => void selectAll: (checked: boolean) => void getSelectedData: () => U[] handleDelete: (deleteApi: () => Promise>, options?: DeleteOptions) => Promise onDelete: (row: U) => Promise onBatchDelete: () => void refresh: () => void fixed: ComputedRef<'right' | undefined> onImport: () => void onExport: () => void } ``` ### Options Interface ```typescript interface Options { formatResult?: (data: T[]) => U[] // Transform API response onSuccess?: () => void // Success callback immediate?: boolean // Auto-fetch on mount (default: true) rowKey?: keyof T // Unique row identifier (default: 'id') crossPageSelect?: boolean // Keep selections across page changes listAPI: (params: { page: number, size: number }) => Promise>> deleteAPI?: (ids: string[]) => Promise> } ``` ### Delete Options Interface ```typescript interface DeleteOptions { title?: string // Confirmation dialog title content?: string // Confirmation dialog content successTip?: string // Success message showModal?: boolean // Show confirmation (default: true) } ``` ### Example Usage ```typescript import { useTable } from '@/hooks' const { loading, tableData, pagination, selectedKeys, search, refresh, onDelete, onBatchDelete } = useTable({ listAPI: (p) => getUserList(p), deleteAPI: (ids) => deleteUser({ ids }), rowKey: 'id', immediate: true }) // In template: // ``` ``` -------------------------------- ### Dynamic Form with Validation and Submission Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/README.md Create dynamic forms with defined columns and handle submissions with automatic success notifications and data refresh. The form supports input and select field types with required validation. ```typescript const form = reactive({ name: '', status: '' }) const columns: FormColumnItem[] = [ { type: 'input', label: 'Name', field: 'name', required: true }, { type: 'select', label: 'Status', field: 'status' } ] const handleSubmit = async () => { const res = await api.add(form) // Success notification handled automatically refresh() } ``` -------------------------------- ### Table Action Column Permissions Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/directives.md Dynamically show action buttons within a table's row based on user permissions. Each button can be protected by a specific 'v-hasPerm' directive. ```vue ``` -------------------------------- ### Add Tab Method Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/stores.md Method to add or update a tab in the tabs store. Requires a TabItem object as input. ```typescript addTab(tab: TabItem): void ``` -------------------------------- ### Delete Options Interface Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/hooks.md Specifies options for customizing the delete confirmation modal. Allows setting titles, content, success messages, and controlling modal visibility. ```typescript interface DeleteOptions { title?: string // Confirmation dialog title content?: string // Confirmation dialog content successTip?: string // Success message showModal?: boolean // Show confirmation (default: true) } ``` -------------------------------- ### getToken Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/utilities.md Retrieves the stored authentication token from localStorage. ```APIDOC ## getToken ### Description Retrieve stored authentication token. ### Method ```typescript const getToken = (): string | null ``` ### Returns `string | null` — Token value or null if not set ``` -------------------------------- ### rgbToHex Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/utilities.md Converts RGB color values to a hexadecimal string representation. ```APIDOC ## rgbToHex ### Description Convert RGB to hexadecimal color. ### Parameters #### Path Parameters - **r** (number) - Required - Red value (0-255) - **g** (number) - Required - Green value (0-255) - **b** (number) - Required - Blue value (0-255) ### Returns `string` — Hex color (e.g., '#FF0000') ### Signature ```typescript export function rgbToHex(r: number, g: number, b: number): string ``` ``` -------------------------------- ### ButtonProps Interface for GiButton Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/types.md Defines the properties for the GiButton component, extending Arco Button properties with semantic action types for common operations. The 'type' property is customized for specific actions. ```typescript export interface ButtonProps extends Omit { type?: 'add' | 'edit' | 'delete' | 'search' | 'reset' | 'upload' | 'import' | 'export' | '' } ``` -------------------------------- ### Table Management Hook Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/README.md Utilizes the `useTable` hook to manage table state, including loading, data, pagination, and selection. It integrates with list and delete APIs for common table operations. ```typescript const { loading, tableData, pagination, selectedKeys, search, refresh, onDelete } = useTable({ listAPI: (p) => getUserList(p), deleteAPI: (ids) => deleteUser({ ids }), rowKey: 'id' }) ``` -------------------------------- ### TypeScript Paths Alias Configuration Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/configuration.md Configure tsconfig.json to use path aliases for cleaner import statements. This helps in organizing project structure and reducing relative path complexity. ```typescript // tsconfig.json compilerOptions.paths = { "@/*": ["./src/*"] } ``` ```typescript import { useUserStore } from '@/stores' // ✅ Instead of ../../../stores import { formatPhone } from '@/utils' // ✅ Instead of ../../../utils import GiButton from '@/components/GiButton' // ✅ Instead of ../../../components ``` -------------------------------- ### isLogin Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/utilities.md Checks if the user is currently logged in by verifying the existence of an authentication token in localStorage. ```APIDOC ## isLogin ### Description Checks if the user is currently logged in by verifying token existence. ### Method ```typescript const isLogin = (): boolean ``` ### Returns `boolean` — True if token exists in localStorage ### Example ```typescript import { isLogin } from '@/utils/auth' if (isLogin()) { // User is authenticated router.push('/home') } else { router.push('/login') } ``` ``` -------------------------------- ### hasPerm Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/utilities.md Checks if the user possesses a specific permission. Super admin permission `*:*:*` grants all permissions. ```APIDOC ## hasPerm ### Description Check if user has specific permission. ### Method ```typescript export function hasPerm(permission: string): boolean ``` ### Parameters #### Path Parameters - **permission** (string) - Required - Permission identifier (e.g., 'user:list') ### Returns `boolean` — True if user has permission or is super admin ### Description Super admin permission marker `*:*:*` grants all permissions. ### Example ```typescript import { hasPerm } from '@/utils/permission' if (hasPerm('user:add')) { // Show add button } ``` ``` -------------------------------- ### useTheme Hook Signature Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/hooks.md Defines the return type for the useTheme hook, including theme state and control functions. ```typescript export function useTheme(): { isDark: Ref theme: ComputedRef<'dark' | 'light'> toggleTheme: () => void setThemeColor: (color: string) => void initThemeColor: () => void } ``` -------------------------------- ### POST /user/logout Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/api-reference/api-endpoints.md Logs out the currently authenticated user. This action invalidates the current session. ```APIDOC ## POST /user/logout ### Description User logout endpoint. Ends the current user session. ### Method POST ### Endpoint /user/logout ### Response #### Success Response (200) - Response body is null upon successful logout. ### Status Codes - `code: 200` — Logout successful - `code: 401` — Not authenticated ``` -------------------------------- ### Dynamic User Route Configuration Type Source: https://github.com/lin-97/gi-demo/blob/master/_autodocs/types.md Defines the structure for dynamic route configurations fetched from the backend, including path, component, hierarchy, and display properties. Used by useRouteStore and route guards. ```typescript export interface UserRouteItem { id: string parentId: string path: string component: string icon: string title: string redirect: string keepAlive: boolean breadcrumb: boolean showInTabs: boolean hidden: boolean type: 1 | 2 | 3 status: 0 | 1 sort: number roles: string[] permission: string alwaysShow: boolean activeMenu: string children: UserRouteItem[] affix: boolean } ```