### Implement Multi-Tab Navigation in Vue.js with Plugin Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Details the integration and usage of a MultiTab component for managing tabbed navigation within a Vue.js application. It shows how to install the component as a Vue plugin and provides examples of using its methods programmatically within components to open, close, and rename tabs, enhancing user experience by allowing users to keep multiple pages open simultaneously. ```javascript import MultiTab from '@/components/MultiTab' // In main.js or plugin Vue.use(MultiTab) // Usage in components export default { name: 'MyComponent', methods: { openNewTab() { // Open new tab with route this.$multiTab.open({ path: '/user/profile', query: { id: 123 } }) }, closeCurrentTab() { // Close current active tab this.$multiTab.closeCurrentPage() }, closeSpecificTab() { // Close tab by route path this.$multiTab.close({ path: '/user/settings' }) }, renameTab() { // Rename tab title this.$multiTab.rename( this.$route.fullPath, 'New Tab Name' ) } }, mounted() { // Open dashboard on component mount this.$multiTab.open({ name: 'Dashboard', path: '/dashboard/analysis' }) } } ``` -------------------------------- ### Bootstrap Initialization - App Setup (JavaScript) Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Initializes the Vue application by loading settings and configurations. It loads layout settings, theme configurations, user tokens, and language preferences from local storage. This function is called during Vue app creation. ```javascript import bootstrap from '@/core/bootstrap' // Called during Vue app creation new Vue({ router, store, i18n, created: bootstrap, // Initialize app settings render: h => h(App) }).$mount('#app') // Bootstrap function loads: // - Layout settings from localStorage // - Theme configurations // - User token // - Language preferences // Manual bootstrap example import storage from 'store' import store from '@/store' import { ACCESS_TOKEN } from '@/store/mutation-types' const initializeApp = () => { // Load token from storage const token = storage.get(ACCESS_TOKEN) if (token) { store.commit('SET_TOKEN', token) } // Load saved settings const settings = { layout: storage.get('TOGGLE_LAYOUT', 'sidemenu'), theme: storage.get('TOGGLE_NAV_THEME', 'dark'), primaryColor: storage.get('TOGGLE_COLOR', '#1890ff'), fixedHeader: storage.get('TOGGLE_FIXED_HEADER', false) } // Apply settings to store Object.keys(settings).forEach(key => { store.commit(`TOGGLE_${key.toUpperCase()}`, settings[key]) }) // Set language store.dispatch('setLang', storage.get('APP_LANGUAGE', 'en-US')) console.log('App initialized with settings:', settings) } ``` -------------------------------- ### Create Reusable Table Component with Pagination in Vue.js Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Demonstrates the creation of a reusable table component in Vue.js using Ant Design Vue's `STable`. This component supports data fetching via a promise-based API, pagination, sorting, and filtering. It includes example configurations for columns and a method to trigger a refresh with search parameters. A template usage example is also provided. ```javascript import { STable } from '@/components' export default { name: 'UserList', components: { STable }, data() { return { columns: [ { title: 'Name', dataIndex: 'name', sorter: true }, { title: 'Email', dataIndex: 'email' }, { title: 'Status', dataIndex: 'status' } ], queryParam: {}, loadData: parameter => { // API call that returns Promise return this.$http.get('/api/users', { params: Object.assign(parameter, this.queryParam) }).then(res => { return { pageNo: res.pageNo, pageSize: res.pageSize, totalCount: res.totalCount, data: res.data } }) } } }, methods: { handleSearch() { this.$refs.table.refresh(true) // Reset to page 1 } } } // Template usage /* */ ``` -------------------------------- ### GET /api/getInfo - Get User Info Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Retrieves the details of the currently authenticated user, including their name, avatar, roles, and permissions. ```APIDOC ## GET /api/getInfo ### Description Retrieves the details of the currently authenticated user, including their name, avatar, roles, and permissions. ### Method GET ### Endpoint /api/getInfo ### Parameters None ### Response #### Success Response (200) - **result** (object) - Contains the user's information. - **name** (string) - The user's name. - **avatar** (string) - The URL to the user's avatar. - **role** (object) - The user's role information. - **permissions** (array) - A list of permissions granted to the user. #### Response Example ```json { "result": { "name": "Admin User", "avatar": "/path/to/avatar.jpg", "role": { "permissions": ["read", "write", "delete"] } } } ``` ``` -------------------------------- ### GET /api/user/list - Get User List Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Retrieves a paginated list of users. Supports filtering by status and sorting by creation time. ```APIDOC ## GET /api/user/list ### Description Retrieves a paginated list of users. Supports filtering by status and sorting by creation time. ### Method GET ### Endpoint /api/user/list ### Parameters #### Query Parameters - **pageNo** (integer) - Optional - The page number for pagination (default: 1). - **pageSize** (integer) - Optional - The number of items per page (default: 10). - **sortField** (string) - Optional - The field to sort by (e.g., 'createTime'). - **sortOrder** (string) - Optional - The order of sorting ('ascend' or 'descend'). - **status** (string) - Optional - Filter users by their status (e.g., 'active'). ### Response #### Success Response (200) - **pageNo** (integer) - The current page number. - **pageSize** (integer) - The number of items per page. - **totalCount** (integer) - The total number of users. - **data** (array) - A list of user objects. - Each user object contains details like name, status, etc. #### Response Example ```json { "pageNo": 1, "pageSize": 10, "totalCount": 100, "data": [ { "id": "1", "name": "User One", "status": "active" }, { "id": "2", "name": "User Two", "status": "inactive" } ] } ``` ``` -------------------------------- ### Get User Information API Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Retrieves details of the currently authenticated user, including roles and permissions. Uses the 'getInfo' function from '@/api/login'. The response includes user name, avatar, roles, and permissions. ```javascript import { getInfo } from '@/api/login' // Fetch current user details const fetchUserInfo = async () => { try { const response = await getInfo() // Response includes user details, avatar, roles, and permissions const { name, avatar, role } = response.result console.log('User:', name) console.log('Permissions:', role.permissions) return response.result } catch (error) { console.error('Failed to get user info:', error) throw error } } ``` -------------------------------- ### Management API: Get All Permissions (JavaScript) Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Retrieves a flat list of all available permissions from the management API. It handles potential errors during the API call and logs the response or error to the console. ```javascript import { getPermissions } from '@/api/manage' // Fetch all permissions const loadPermissions = async () => { try { const response = await getPermissions() // Returns flat list of all permissions console.log('Available permissions:', response) return response } catch (error) { console.error('Failed to load permissions:', error) throw error } } ``` -------------------------------- ### GET /api/role/list - Get Role List Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Fetches a list of available roles, including their names and associated permissions. Used for managing role-based access control. ```APIDOC ## GET /api/role/list ### Description Fetches a list of available roles, including their names and associated permissions. Used for managing role-based access control. ### Method GET ### Endpoint /api/role/list ### Parameters #### Query Parameters - **pageNo** (integer) - Optional - The page number for pagination (default: 1). - **pageSize** (integer) - Optional - The number of items per page (default: 20). ### Response #### Success Response (200) - **data** (array) - A list of role objects. - Each role object contains: - **name** (string) - The name of the role. - **permissions** (string) - A comma-separated string of permissions associated with the role. #### Response Example ```json [ { "name": "Administrator", "permissions": "read,write,delete,manage" }, { "name": "Editor", "permissions": "read,write" } ] ``` ``` -------------------------------- ### Get User List API Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Fetches a paginated list of users, supporting filtering by status and sorting by creation time. It uses the 'getUserList' function from '@/api/manage' with parameters for page number, page size, sort field, sort order, and status. The response includes the total count and user data. ```javascript import { getUserList } from '@/api/manage' // Fetch users with pagination const loadUsers = async () => { try { const response = await getUserList({ pageNo: 1, pageSize: 10, sortField: 'createTime', sortOrder: 'descend', status: 'active' }) // Response: { pageNo: 1, pageSize: 10, totalCount: 100, data: [...] } console.log('Users:', response.data) console.log('Total:', response.totalCount) return response } catch (error) { console.error('Failed to load users:', error) throw error } } ``` -------------------------------- ### Management API: Get Organization Tree (JavaScript) Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Fetches the hierarchical organization structure from the management API. It includes a recursive function to render the tree structure to the console, displaying the name of each organization at its respective level. ```javascript import { getOrgTree } from '@/api/manage' // Load organization hierarchy const loadOrgStructure = async () => { try { const response = await getOrgTree() // Response is tree structure with nested children const renderTree = (nodes, level = 0) => { nodes.forEach(node => { console.log(' '.repeat(level) + node.name) if (node.children && node.children.length > 0) { renderTree(node.children, level + 1) } }) } renderTree(response) return response } catch (error) { console.error('Failed to load org tree:', error) throw error } } ``` -------------------------------- ### Get Role List API Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Retrieves a list of available roles along with their associated permissions, used for role-based access control. This function calls 'getRoleList' from '@/api/manage', specifying pagination parameters. It then logs the name and permissions of each role. ```javascript import { getRoleList } from '@/api/manage' // Get all roles const loadRoles = async () => { try { const response = await getRoleList({ pageNo: 1, pageSize: 20 }) response.data.forEach(role => { console.log(`Role: ${role.name}, Permissions: ${role.permissions}`) }) return response.data } catch (error) { console.error('Failed to load roles:', error) throw error } } ``` -------------------------------- ### POST /api/get2step - Two-Step Verification Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Validates a two-step verification code provided by the user. ```APIDOC ## POST /api/get2step ### Description Validates a two-step verification code provided by the user. ### Method POST ### Endpoint /api/get2step ### Parameters #### Request Body - **stepCode** (string) - Required - The two-step verification code. ### Request Example ```json { "stepCode": "123456" } ``` ### Response #### Success Response (200) - Indicates successful validation of the two-step code. #### Response Example ```json { "status": "success", "message": "Verification successful" } // Example response structure ``` ``` -------------------------------- ### Configure Dynamic Routes with Permissions in Vue.js Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Defines how to configure application routes dynamically with permission-based access control using JavaScript. It shows a sample route structure including nested children and meta fields for title, icon, keep-alive, and permissions. It also demonstrates accessing the current route and navigating programmatically within a Vue component. ```javascript import { asyncRouterMap } from '@/config/router.config' // Route structure with nested children const exampleRoute = { path: '/dashboard', name: 'dashboard', component: () => import('@/views/dashboard/Analysis'), meta: { title: 'Dashboard', icon: 'dashboard', keepAlive: true, permission: ['dashboard'] } } // Access routes in component export default { name: 'MyComponent', computed: { currentRoute() { return this.$route } }, methods: { navigateToDashboard() { this.$router.push('/dashboard/analysis') }, navigateWithParams() { this.$router.push({ name: 'UserProfile', params: { id: 123 }, query: { tab: 'settings' } }) } } } ``` -------------------------------- ### Implement Router Permission Guard in Vue.js Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Provides a detailed implementation of a router navigation guard in JavaScript for handling authentication and authorization. The guard intercepts navigation attempts, checks for authentication tokens, fetches user information, dynamically generates routes, and manages redirection based on user roles and token presence. It also includes NProgress for loading indicators. ```javascript // Navigation guard flow (from permission.js) import router from './router' import store from './store' import NProgress from 'nprogress' // Example of how the guard works router.beforeEach(async (to, from, next) => { NProgress.start() const token = localStorage.getItem('Access-Token') if (token) { if (to.path === '/user/login') { next({ path: '/dashboard/workplace' }) } else { // Check if user info loaded if (store.getters.roles.length === 0) { try { // Fetch user info and generate routes const userInfo = await store.dispatch('GetInfo') await store.dispatch('GenerateRoutes', userInfo) // Add dynamic routes store.getters.addRouters.forEach(route => { router.addRoute(route) }) next({ ...to, replace: true }) } catch (error) { console.error('Navigation error:', error) await store.dispatch('Logout') next({ path: '/user/login' }) } } else { next() } } } else { // No token - redirect to login if (['login', 'register'].includes(to.name)) { next() } else { next({ path: '/user/login', query: { redirect: to.fullPath } }) } } }) router.afterEach(() => { NProgress.done() }) ``` -------------------------------- ### POST /api/login - User Login Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Authenticates a user by providing username and password credentials. It can also handle 'remember me' functionality and captcha verification. ```APIDOC ## POST /api/login ### Description Authenticates a user by providing username and password credentials. It can also handle 'remember me' functionality and captcha verification. ### Method POST ### Endpoint /api/login ### Parameters #### Request Body - **username** (string) - Required - The username for login. - **password** (string) - Required - The password for login. - **remember_me** (boolean) - Optional - Whether to keep the user logged in. - **captcha** (string) - Optional - The captcha code for verification. ### Request Example ```json { "username": "admin", "password": "admin123", "remember_me": true, "captcha": "12345" } ``` ### Response #### Success Response (200) - **result** (object) - Contains the authentication token. - **token** (string) - The JWT token for authenticated sessions. #### Response Example ```json { "result": { "token": "jwt-token-here" } } ``` ``` -------------------------------- ### Vuex Store: User Authentication Actions (JavaScript) Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Defines Vuex store actions for managing user authentication, including logging in with provided credentials, fetching user information after login, and logging out the user. These actions interact with the Vuex store to update the application's authentication state. ```javascript import store from '@/store' // Login action const performLogin = async () => { try { await store.dispatch('Login', { username: 'admin', password: 'password123', remember_me: true }) console.log('Login successful, token stored') console.log('Current token:', store.state.user.token) } catch (error) { console.error('Login failed:', error) throw error } } // Get user info action const loadUserInfo = async () => { try { const userInfo = await store.dispatch('GetInfo') console.log('User name:', store.state.user.name) console.log('User roles:', store.state.user.roles) console.log('Avatar:', store.state.user.avatar) return userInfo } catch (error) { console.error('Failed to get user info:', error) throw error } } // Logout action const performLogout = async () => { try { await store.dispatch('Logout') console.log('Logged out successfully') console.log('Token cleared:', store.state.user.token === '') // Redirect to login page window.location.href = '/user/login' } catch (error) { console.error('Logout error:', error) } } ``` -------------------------------- ### HTTP Request Configuration: Axios Instance (JavaScript) Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Configures a custom Axios instance for making HTTP requests. It includes a base URL, timeout, and interceptors to automatically add authentication tokens to requests and handle common response errors like 401 Unauthorized. ```javascript import axios from 'axios' import storage from 'store' import { ACCESS_TOKEN } from '@/store/mutation-types' // Create configured axios instance const request = axios.create({ baseURL: process.env.VUE_APP_API_BASE_URL, timeout: 6000 }) // Request interceptor - add auth token request.interceptors.request.use(config => { const token = storage.get(ACCESS_TOKEN) if (token) { config.headers[ACCESS_TOKEN] = token } return config }, error => { return Promise.reject(error) }) // Response interceptor - handle errors request.interceptors.response.use( response => response.data, error => { if (error.response?.status === 401) { console.log('Unauthorized - redirecting to login') // Handle unauthorized access } return Promise.reject(error) } ) // Example usage const fetchData = async () => { try { const data = await request({ url: '/api/data', method: 'get', params: { id: 123 } }) console.log('Data:', data) return data } catch (error) { console.error('Request failed:', error) throw error } } ``` -------------------------------- ### CDN Script Inclusion Placeholder (HTML) Source: https://github.com/vuecomponent/ant-design-vue-pro/blob/master/public/index.html These are EJS template placeholders for including CSS and JavaScript files from a CDN. They are intended to be processed by a build tool and do not contain executable code directly. They are used to dynamically add external resources. ```ejs <% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.css) { %> <% } %> ``` ```ejs <% for (var i in htmlWebpackPlugin.options.cdn && htmlWebpackPlugin.options.cdn.js) { %> <% } %> ``` -------------------------------- ### Login User Authentication API Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Handles user login with username and password. Requires 'login' function from '@/api/login'. Returns a response object containing a JWT token upon successful authentication. ```javascript import { login } from '@/api/login' // Authenticate user with credentials const loginUser = async () => { try { const response = await login({ username: 'admin', password: 'admin123', remember_me: true, captcha: '12345' }) // Response structure: { result: { token: 'jwt-token-here' } } console.log('Login successful:', response.result.token) return response } catch (error) { console.error('Login failed:', error) throw error } } ``` -------------------------------- ### Ant Design Pro Loading Wrapper CSS Source: https://github.com/vuecomponent/ant-design-vue-pro/blob/master/public/index.html This CSS defines the styling for the first-loading wrapper used in Ant Design Vue Pro. It includes properties for layout, size, and animation of loading indicators. It is a self-contained CSS block. ```css .first-loading-wrp{display:flex;justify-content:center;align-items:center;flex-direction:column;min-height:420px;height:100%}.first-loading-wrp>h1{font-size:128px}.first-loading-wrp .loading-wrp{padding:98px;display:flex;justify-content:center;align-items:center}.dot{animation:antRotate 1.2s infinite linear;transform:rotate(45deg);position:relative;display:inline-block;font-size:32px;width:32px;height:32px;box-sizing:border-box}.dot i{width:14px;height:14px;position:absolute;display:block;background-color:#1890ff;border-radius:100%;transform:scale(.75);transform-origin:50% 50%;opacity:.3;animation:antSpinMove 1s infinite linear alternate}.dot i:nth-child(1){top:0;left:0}.dot i:nth-child(2){top:0;right:0;-webkit-animation-delay:.4s;animation-delay:.4s}.dot i:nth-child(3){right:0;bottom:0;-webkit-animation-delay:.8s;animation-delay:.8s}.dot i:nth-child(4){bottom:0;left:0;-webkit-animation-delay:1.2s;animation-delay:1.2s}@keyframes antRotate{to{-webkit-transform:rotate(405deg);transform:rotate(405deg)}}@-webkit-keyframes antRotate{to{-webkit-transform:rotate(405deg);transform:rotate(405deg)}}@keyframes antSpinMove{to{opacity:1}}@-webkit-keyframes antSpinMove{to{opacity:1}} ``` -------------------------------- ### Two-Step Verification API Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Validates a two-step authentication code. It utilizes the 'get2step' function from '@/api/login' and expects a 'stepCode' as input. The response from this API call is logged to the console. ```javascript import { get2step } from '@/api/login' // Validate 2FA code const validateTwoStep = async (code) => { try { const response = await get2step({ stepCode: code }) console.log('2FA validation:', response) return response } catch (error) { console.error('2FA validation failed:', error) throw error } } ``` -------------------------------- ### POST /api/getSmsCaptcha - SMS Captcha Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Requests an SMS verification code to be sent to a specified phone number. ```APIDOC ## POST /api/getSmsCaptcha ### Description Requests an SMS verification code to be sent to a specified phone number. ### Method POST ### Endpoint /api/getSmsCaptcha ### Parameters #### Request Body - **mobile** (string) - Required - The phone number to send the SMS to. ### Request Example ```json { "mobile": "+1234567890" } ``` ### Response #### Success Response (200) - Indicates that the SMS verification code has been sent successfully. #### Response Example ```json { "message": "SMS sent successfully" } // Example response structure ``` ``` -------------------------------- ### Management API: Save Service Record (JavaScript) Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Handles the creation or update of a service record via the management API. It automatically detects if a service needs to be created (id === 0) or updated (id !== 0) and includes logging for success or failure. ```javascript import { saveService } from '@/api/manage' // Create new service (id === 0) const createService = async () => { try { const response = await saveService({ id: 0, name: 'User Service', description: 'Manages user operations', status: 'active' }) console.log('Service created:', response) return response } catch (error) { console.error('Failed to create service:', error) throw error } } // Update existing service (id !== 0) const updateService = async (serviceId) => { try { const response = await saveService({ id: serviceId, name: 'Updated Service Name', status: 'inactive' }) console.log('Service updated:', response) return response } catch (error) { console.error('Failed to update service:', error) throw error } } ``` -------------------------------- ### POST /api/logout - User Logout Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Logs out the current user by terminating their session and clearing any authentication tokens. ```APIDOC ## POST /api/logout ### Description Logs out the current user by terminating their session and clearing any authentication tokens. ### Method POST ### Endpoint /api/logout ### Parameters None ### Request Example ```json {} // Empty request body is expected ``` ### Response #### Success Response (200) - Indicates successful logout. #### Response Example ```json { "message": "Logout successful" } // Example response structure ``` ``` -------------------------------- ### I18n - Internationalization in Vue Components (JavaScript) Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Implements multi-language support within Vue components using Vue I18n. It allows switching languages, translating text using keys, and handling translations with parameters. The current locale is logged on mount. ```javascript import Vue from 'vue' import VueI18n from 'vue-i18n' import storage from 'store' import { APP_LANGUAGE } from '@/store/mutation-types' // In component usage export default { name: 'MyComponent', computed: { locale() { return this.$i18n.locale } }, methods: { switchLanguage(lang) { // Change language this.$i18n.locale = lang storage.set(APP_LANGUAGE, lang) this.$store.dispatch('setLang', lang) }, translateText() { // Use translation key const greeting = this.$t('menu.home') const userName = this.$t('user.name') console.log(greeting, userName) // Translation with parameters const message = this.$t('user.welcome', { name: 'John' }) console.log(message) return message } }, mounted() { // Get current language console.log('Current language:', this.$i18n.locale) // Available: 'en-US', 'zh-CN' this.switchLanguage('en-US') } } // Template usage /* */ ``` -------------------------------- ### SMS Captcha Request API Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Requests an SMS verification code to be sent to a specified phone number. This function uses 'getSmsCaptcha' from '@/api/login' and takes a 'phoneNumber' as an argument. A success message is logged upon completion. ```javascript import { getSmsCaptcha } from '@/api/login' // Send SMS captcha to phone number const sendSmsCode = async (phoneNumber) => { try { const response = await getSmsCaptcha({ mobile: phoneNumber }) console.log('SMS sent successfully') return response } catch (error) { console.error('Failed to send SMS:', error) throw error } } ``` -------------------------------- ### User Logout API Source: https://context7.com/vuecomponent/ant-design-vue-pro/llms.txt Logs out the current user by terminating their session and clearing the authentication token. It calls the 'logout' function from '@/api/login', then removes the token from local storage and redirects to the login page. ```javascript import { logout } from '@/api/login' // Logout current user const logoutUser = async () => { try { await logout() console.log('User logged out successfully') // Clear local storage and redirect to login localStorage.removeItem('Access-Token') window.location.href = '/user/login' } catch (error) { console.error('Logout failed:', error) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.