### uni-app Frontend Upload Example Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-ext-storage-basic.md Example of how to implement file uploads from a uni-app frontend using cloud objects and `uni.uploadFile`. ```APIDOC ## uni-app Frontend Upload Example ### Description Demonstrates how to select an image using `uni.chooseImage` and upload it via a uniCloud cloud object. ### Code Snippet ```javascript // Select image and initiate upload uni.chooseImage({ count: 1, // Number of images to choose success: async (res) => { const filePath = res.tempFilePaths[0]; uni.showLoading({ title: "Uploading...", mask: true }); // Import the cloud object that handles upload parameters const extStorageCo = uniCloud.importObject("ext-storage-co"); // Get upload options from the cloud object const uploadFileOptionsRes = await extStorageCo.getUploadFileOptions({ cloudPath: `images/${Date.now()}.jpg` // Define the cloud path }); // Execute the upload using uni.uploadFile const uploadTask = uni.uploadFile({ ...uploadFileOptionsRes.uploadFileOptions, // Spread the upload parameters filePath: filePath, // Local file path success: (uploadFileRes) => { if (uploadFileRes.statusCode === 200) { const result = { cloudPath: uploadFileOptionsRes.cloudPath, fileID: uploadFileOptionsRes.fileID, fileURL: uploadFileOptionsRes.fileURL }; console.log("Upload successful", result); } }, fail: (err) => { console.log("Upload failed", err); } }); // Monitor upload progress uploadTask.onProgressUpdate((res) => { console.log("Upload progress", res.progress + "%"); }); uni.hideLoading(); } }); ``` ``` -------------------------------- ### Cloud Object Basic Template Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-permission-system.md A foundational template for creating VK Cloud Objects, including initialization, request pre-processing (_before), request post-processing (_after), and example functions. ```APIDOC ## Cloud Object Basic Template ### Description This template provides the basic structure for a VK Cloud Object, which is a collection of cloud functions within a single JavaScript file. It includes hooks for pre- and post-request processing. ### Method N/A (This is a structural template) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript 'use strict'; var vk; // Global vk instance // Table names involved const dbName = { //test: "vk-test", // Test table }; var db = uniCloud.database(); // Global database reference var _ = db.command; // Database operators var $ = _.aggregate; // Aggregate query operators var cloudObject = { isCloudObject: true, // Mark as rapid development mode /** * Pre-request processing, mainly for pre-processing before calling methods, usually for interceptors, unified identity authentication, parameter validation, global object definition, etc. */ _before: async function() { vk = this.vk; // Define vk as a global object // let { customUtil, uniID, config, pubFun } = this.getUtil(); // Get utility package }, /** * Post-request processing, mainly for processing the return result or thrown errors of the current call method */ _after: async function(options) { let { err, res } = options; if (err) { return; // If the method throws an error, directly return; do not process } return res; }, /** * Template function * @url client/user.getInfo Frontend call URL parameter address */ getInfo: async function(data) { let { uid } = this.getClientInfo(); // Get client information let userInfo = await this.getUserInfo(); // Get the currently logged-in user's info let res = { code: 0, msg: '' }; // Business logic start----------------------------------------------------------- console.log("Request parameters", data); res.userInfo = userInfo; // Return the current logged-in user information to the frontend // Business logic end------------------------------------------------------------- return res; }, /** * Template function * @url client/user.getList Frontend call URL parameter address */ getList: async function(data) { let { uid, filterResponse, originalParam } = this.getClientInfo(); // Get client information let res = { code: 0, msg: '' }; // Business logic start----------------------------------------------------------- console.log("Request parameters", data); // Business logic end------------------------------------------------------------- return res; } }; module.exports = cloudObject; ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Vue Component Structure and Best Practices Source: https://github.com/382444017/vk-unicloud/blob/master/frontend-component-development.md Demonstrates the basic structure of a Vue component, including template, script setup, and scoped styles. It highlights the use of defineProps for attributes, defineEmits for events, ref and computed for reactive data, and scoped CSS for style isolation. ```vue ``` -------------------------------- ### Check User Roles and Permissions using VK Unicloud Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-permission-system.md Provides examples of checking user roles and permissions using the vk.userCenter utility. It demonstrates how to check for a specific role, any of multiple permissions, or all specified permissions. ```javascript // 检查用户是否有特定角色 let hasRole = await vk.userCenter.hasRole({ uid, role: 'admin' }); // 检查用户是否有多个权限中的任意一个 let hasAnyPermission = await vk.userCenter.hasAnyPermission({ uid, permissions: ['user-view', 'user-manage'] }); // 检查用户是否有所有指定权限 let hasAllPermissions = await vk.userCenter.hasAllPermissions({ uid, permissions: ['user-view', 'user-edit'] }); ``` -------------------------------- ### Setup Payment Database Indexes in JavaScript Source: https://github.com/382444017/vk-unicloud/blob/master/vk-pay-error-handling.md Optimizes database performance by creating necessary indexes on the 'payment_orders' table. It sets up unique indexes for order numbers and non-unique indexes for user IDs, status, and creation dates. This function assumes a 'vk.baseDao' object for database operations. ```javascript // 支付表索引优化 async function setupPaymentIndexes() { // 创建订单号索引 await vk.baseDao.createIndex({ dbName: "payment_orders", field: "out_trade_no", unique: true }); // 创建用户ID索引 await vk.baseDao.createIndex({ dbName: "payment_orders", field: "user_id" }); // 创建状态索引 await vk.baseDao.createIndex({ dbName: "payment_orders", field: "status" }); // 创建时间索引 await vk.baseDao.createIndex({ dbName: "payment_orders", field: "create_date" }); } ``` -------------------------------- ### Perform Cloud-Side HTTP Requests with VK Unicloud Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-best-practices.md Illustrates how to make HTTP requests from within VK Unicloud functions. Covers various methods (POST, GET), data types (JSON, text, binary), setting headers, timeouts, using proxies (Aliyun specific), and encrypted communication. ```javascript // 云端HTTP请求(必须使用await) const response = await vk.request({ url: 'https://api.example.com/data', method: 'POST', header: { 'content-type': 'application/json', 'authorization': 'Bearer token' }, data: { key: 'value' }, timeout: 10000 }); console.log('请求结果:', response); // 请求文本格式数据 const textResponse = await vk.request({ url: 'https://api.example.com/text', method: 'GET', dataType: 'text' }); // 请求二进制数据 const binaryData = await vk.request({ url: 'https://example.com/image.jpg', method: 'GET', dataType: 'default' }); // 转换为base64 const base64 = "data:image/png;base64," + binaryData.toString('base64') // 使用代理请求(仅阿里云) const proxyResponse = await vk.request({ url: 'https://api.example.com/data', useProxy: true, data: { key: 'value' } }); // 加密通信 const encryptResponse = await vk.request({ url: 'https://your-domain.com/http/router/api/test', encrypt: true, header: { 'uni-id-token': userToken, 'vk-appid': '__UNI__12345', 'vk-platform': 'h5' }, data: { a: 1, b: 2 } }); ``` -------------------------------- ### Responsive Design with Media Queries Source: https://github.com/382444017/vk-unicloud/blob/master/frontend-style-guide.md This code demonstrates responsive design principles using CSS media queries. It applies different styles based on screen width, starting with mobile-first design and progressively enhancing for tablet and desktop views. This ensures optimal layout and user experience across various devices. ```css /* 移动端优先 */ .container { padding: 20rpx; width: 100%; } /* 平板端 */ @media (min-width: 768px) { .container { padding: 40rpx; max-width: 750px; margin: 0 auto; } } /* 桌面端 */ @media (min-width: 1024px) { .极狐tainer { padding: 60rpx; max-width: 1200px; } } ``` -------------------------------- ### 使用 Context7 检索文档 (Bash) Source: https://github.com/382444017/vk-unicloud/blob/master/README.md 通过 Context7 工具在 VK Unicloud 项目中检索文档。该命令接受一个搜索关键词作为参数,用于查找相关的文档内容。 ```bash # 使用 Context7 检索文档 context7 search "你的搜索关键词" ``` -------------------------------- ### Successful Responses Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-response-format.md Examples of successful responses, with and without data, and for list data retrieval. ```APIDOC ## Successful Responses ### Description These examples demonstrate successful operations. A `code` of 0 signifies success, triggering the `success` callback in `vk.callFunction`. ### Method N/A ### Endpoint N/A ### Response #### Basic Success Response (code: 0) - **code** (number) - 0 for success. - **msg** (string) - Success message. #### Response Example (Basic) ```json { "code": 0, "msg": "Operation successful" } ``` #### Success Response with Data - **code** (number) - 0 for success. - **msg** (string) - Success message. - **data** (object) - Contains specific data, like user information. #### Response Example (with data) ```json { "code": 0, "msg": "Successfully retrieved", "data": { "userInfo": { "_id": "user001", "nickname": "Zhang San", "avatar": "https://example.com/avatar.jpg" } } } ``` #### List Data Response - **code** (number) - 0 for success. - **msg** (string) - Success message. - **data** (object) - Contains list data with pagination information. - **rows** (array) - The list of items. - **total** (number) - Total number of items. - **pageIndex** (number) - Current page index. - **pageSize** (number) - Items per page. - **hasMore** (boolean) - Indicates if there are more items. #### Response Example (List Data) ```json { "code": 0, "msg": "Successfully retrieved", "data": { "rows": [ { "_id": "1", "title": "Title 1" }, { "_id": "2", "title": "Title 2" } ], "total": 100, "pageIndex": 1, "pageSize": 10, "hasMore": true } } ``` ``` -------------------------------- ### 云对象权限控制配置 Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-object-development.md 此代码段展示了如何为云对象的方法配置权限。通过 `_permission` 对象,可以指定哪些方法需要登录('login')或特定的管理员权限('admin'),哪些方法是公开的([])。`_before` 函数可用于实现具体的权限验证逻辑。 ```javascript var cloudObject = { // 权限配置 _permission: { // 需要登录的方法 'getUserInfo': ['login'], // 需要特定权限的方法 'deleteUser': ['admin'], // 公开方法(无需权限) 'getPublicData': [] }, _before: async function() { // 权限验证逻辑 let methodName = this.getMethodName(); let permissions = this._permission[methodName]; if (permissions && permissions.includes('login')) { let { uid } = this.getClientInfo(); if (!uid) { throw new Error('请先登录'); } } } }; ``` -------------------------------- ### Get Temporary File URL Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-ext-storage-basic.md Generates a temporary, time-limited URL for accessing files, especially private ones. ```APIDOC ## POST /getTempFileURL ### Description Generates temporary URLs for accessing files in the cloud storage. ### Method POST ### Endpoint /getTempFileURL ### Parameters #### Request Body - **fileList** (Array) - Required - A list of file identifiers (e.g., fileID, cloudPath). - **expiresIn** (number) - Optional - The validity period for the temporary URL in seconds. ### Request Example ```json { "fileList": ["qiniu://test.jpg"], "expiresIn": 3600 } ``` ### Response #### Success Response (200) - **fileList** (Array) - A list of objects, each containing the temporary URL for a file. - **fileID** (string) - The identifier of the file. - **tempFileURL** (string) - The generated temporary URL. - **status** (string) - The status of the URL generation (e.g., 'ok'). #### Response Example ```json { "fileList": [ { "fileID": "qiniu://test.jpg", "tempFileURL": "https://example.com/download/test.jpg?token=...", "status": "ok" } ] } ``` ``` -------------------------------- ### 获取临时下载链接 Source: https://github.com/382444017/vk-unicloud/blob/master/ext-storage-basic-config.md 为指定的文件列表生成临时的下载链接,并可设置链接的有效期。 ```APIDOC ## 获取临时下载链接 为指定的文件列表生成临时的下载链接,并可设置链接的有效期。 ### Method ```javascript extStorageManager.getTempFileURL({ fileList: ["qiniu://test.jpg"], // 文件地址列表 expiresIn: 3600 // 有效期(秒) }); ``` ### Parameters #### Request Body - **fileList** (Array) - Required - 文件地址列表,支持 `fileID`、`cloudPath`、`fileURL` 格式。 - **expiresIn** (number) - Optional - 链接有效期(秒),默认为 3600 秒。 ``` -------------------------------- ### Get Upload File Options Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-ext-storage-basic.md Retrieves parameters required for uploading files to the extension storage. This is typically called from a cloud object. ```APIDOC ## POST /getUploadFileOptions ### Description Retrieves parameters required for uploading files to the extension storage. ### Method POST ### Endpoint /getUploadFileOptions ### Parameters #### Request Body - **cloudPath** (string) - Required - The destination path for the file in cloud storage. - **allowUpdate** (boolean) - Optional - Whether to allow overwriting existing files. - **fsizeLimit** (number) - Optional - The maximum allowed file size in bytes. - **expiresIn** (number) - Optional - The expiration time for the upload token in seconds. - **mimeLimit** (string) - Optional - A MIME type or wildcard to restrict allowed file types. ### Request Example ```json { "cloudPath": "images/myImage.jpg", "allowUpdate": false, "fsizeLimit": 10485760, "expiresIn": 3600, "mimeLimit": "image/*" } ``` ### Response #### Success Response (200) - **uploadFileOptions** (object) - Contains the parameters for the `uni.uploadFile` method. - **cloudPath** (string) - The cloud path where the file will be uploaded. - **fileID** (string) - The unique identifier for the uploaded file. - **fileURL** (string) - The URL to access the uploaded file. #### Response Example ```json { "uploadFileOptions": { "url": "https://example.com/upload", "filePath": "/path/to/local/file", "name": "file", "header": { "Authorization": "Bearer YOUR_TOKEN" }, "formData": { "key": "images/myImage.jpg" } }, "cloudPath": "images/myImage.jpg", "fileID": "someFileID123", "fileURL": "https://example.com/images/myImage.jpg" } ``` ``` -------------------------------- ### Error Responses Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-response-format.md Examples of failure responses, covering general errors, business logic errors, validation errors, and permission errors. ```APIDOC ## Error Responses ### Description Failure responses occur when the `code` is non-zero. These trigger the `fail` callback in `vk.callFunction` and automatically execute `vk.alert(msg)`. ### Method N/A ### Endpoint N/A ### Response #### General Error Response - **code** (number) - Non-zero error code. - **msg** (string) - Error message. #### Response Example (General Error) ```json { "code": -1, "msg": "Operation failed" } ``` #### Business Logic Error - **code** (number) - Specific business error code (e.g., 1001). - **msg** (string) - Description of the business logic failure. #### Response Example (Business Logic Error) ```json { "code": 1001, "msg": "Exchange failed, insufficient points" } ``` #### Parameter Validation Error - **code** (number) - Parameter validation error code (e.g., 1002). - **msg** (string) - Description of the parameter error. #### Response Example (Parameter Validation Error) ```json { "code": 1002, "msg": "Invalid parameters: User ID cannot be empty" } ``` #### Permission Validation Error - **code** (number) - Permission error code (e.g., 1003). - **msg** (string) - Description of the permission issue. #### Response Example (Permission Validation Error) ```json { "code": 1003, "msg": "Insufficient permissions to perform this operation" } ``` #### Error Response with Detailed Errors - **code** (number) - Error code indicating validation failure (e.g., 1004). - **msg** (string) - General error message. - **data** (object) - Contains specific field validation errors. - **errors** (object) - Maps field names to their validation error messages. #### Response Example (Detailed Errors) ```json { "code": 1004, "msg": "Data validation failed", "data": { "errors": { "username": "Username must be at least 3 characters long", "email": "Invalid email format" } } } ``` ``` -------------------------------- ### 默认存储配置 (JavaScript) Source: https://github.com/382444017/vk-unicloud/blob/master/frontend-file-upload.md 展示了如何在`app.config.js`中配置VK框架的默认云存储提供商。代码包含了`defaultProvider`的设置,以及针对`extStorage`(如七牛云)和`aliyun`(阿里云OSS)的详细配置选项,如域名、目录、Access Key等。 ```javascript export default { service: { cloudStorage: { // 默认存储提供商 defaultProvider: "unicloud", // unicloud | extStorage | aliyun // 扩展存储配置 extStorage: { provider: "qiniu", dirname: "public", domain: "cdn.example.com", groupUserId: false }, // 阿里云OSS配置 aliyun: { uploadData: { OSSAccessKeyId: "", policy: "", signature: "" }, action: "https://bucket.oss-cn-hangzhou.aliyuncs.com", dirname: "public", host: "https://cdn.example.com" } } } } ``` -------------------------------- ### 云对象基本模板 Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-object-development.md 这是一个云对象的JavaScript模板,包含了全局变量定义、请求前处理 (_before)、请求后处理 (_after) 以及示例方法(get极速开发, getList)。它利用VK框架进行云端开发,支持数据库操作和客户端信息获取。 ```javascript 'use strict'; var vk; // 涉及的表名 const dbName = { //test: "vk-test", // 测试表 }; var db = uniCloud.database(); // 全局数据库引用 var _ = db.command; // 数据库操作符 var $ = _.aggregate; // 聚合查询操作符 var cloudObject = { isCloudObject: true, // 标记为极速开发模式 /** * 请求前处理,主要用于调用方法之前进行预处理,一般用于拦截器、统一的身份验证、参数校验、定义全局对象等。 */ _before: async function() { vk = this.vk; // 将vk定义为全局对象 // let { customUtil, uniID, config, pubFun } = this.getUtil(); // 获取工具包 }, /** * 请求后处理,主要用于处理本次调用方法的返回结果或者抛出的错误 */ _after: async function(options) { let { err, res } = options; if (err) { return; // 如果方法抛出错误,直接return;不处理 } return res; }, /** * 模板函数 * @url client/user.getInfo 前端调用的url参数地址 */ get极速开发: async function(data) { let { uid } = this.getClientInfo(); // 获取客户端信息 let userInfo = await this.getUserInfo(); // 获取当前登录的用户极速开发 let res = { code: 0, msg: '' }; // 业务逻辑开始----------------------------------------------------------- console.log("请求参数", data); res.userInfo = userInfo; // 返回前端当前登录的用户信息 // 业务逻辑结束----------------------------------------------------------- return res; }, /** * 模板函数 * @url client/user.getList 前端调用的url参数地址 */ getList: async function(data) { let { uid, filterResponse, originalParam } = this.getClientInfo(); // 获取客户端信息 let res = { code: 0, msg: '' }; // 业务逻辑开始----------------------------------------------------------- console.log("请求参数", data); // 业务逻辑结束----------------------------------------------------------- return res; } }; module.exports = cloudObject; ``` -------------------------------- ### 删除文件 Source: https://github.com/382444017/vk-unicloud/blob/master/ext-storage-basic-config.md 根据提供的文件列表,删除云端存储中的文件。 ```APIDOC ## 删除文件 根据提供的文件列表,删除云端存储中的文件。 ### Method ```javascript extStorageManager.deleteFile({ fileList: ["qiniu://test.jpg"] // 待删除的文件地址列表 }); ``` ### Parameters #### Request Body - **fileList** (Array) - Required - 待删除的文件地址列表,支持 `fileID`、`cloudPath`、`fileURL` 格式。 ``` -------------------------------- ### 修改文件状态 Source: https://github.com/382444017/vk-unicloud/blob/master/ext-storage-basic-config.md 修改文件的访问权限,可以将其设置为私有或公共访问。 ```APIDOC ## 修改文件状态 修改文件的访问权限,可以将其设置为私有或公共访问。 ### Method ```javascript extStorageManager.updateFileStatus({ fileID: "qiniu://test.jpg", isPrivate: true // true 私有 false 公共 }); ``` ### Parameters #### Request Body - **fileID** (string) - Required - 文件的唯一标识符。 - **isPrivate** (boolean) - Required - 设置文件权限,`true` 表示私有,`false` 表示公共。 ``` -------------------------------- ### Vuex Simplified API Usage Source: https://github.com/382444017/vk-unicloud/blob/master/frontend-state-management.md Demonstrates the recommended simplified API for interacting with Vuex state in the VK framework. It covers getting and setting state properties directly using `vk.getVuex` and `vk.setVuex`. ```javascript // 获取 Vuex 数据 const userInfo = vk.getVuex('$user.userInfo') const avatar = vk.getVuex('$user.userInfo.avatar') // 更新 Vuex 数据 vk.setVuex('$user.userInfo.avatar', newAvatar) vk.setVuex('$user.loginStatus', true) // 在模板中使用 // {{ vk.getVuex('$user.userInfo.nickname') }} ``` -------------------------------- ### VK-UniCloud 云端目录结构 Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-framework-overview.md 展示了VK-UniCloud项目的标准云端目录结构,包括云函数、数据库和云对象等关键部分。 ```tree uniCloud-alipay/ ├── cloudfunctions/ # 云函数目录 │ ├── common/ # 公共模块 │ │ ├── uni-config-center/ # 配置中心 │ │ ├── uni-id/ # 用户身份管理 │ │ └── vk-unicloud/ # VK框架核心 │ └── router/ # 路由云函数 │ ├── service/ # 业务逻辑 │ │ ├── admin/ # 管理端业务 │ │ ├── client/ # 客户端业务 │ │ └── user/ # 用户中心 │ └── index.js # 入口文件 ├── database/ # 数据库Schema │ ├── uni-id-users.schema.json │ └── custom-table.schema.json └── cloudobjects/ # 云对象目录(可选) ``` -------------------------------- ### Get Cloud Function Request ID with VK Unicloud Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-best-practices.md Retrieves the unique request ID for the current cloud function execution using the VK Unicloud library. This ID can be useful for logging and tracing requests. ```javascript // 获取云函数请求ID const requestId = vk.pubfn.getUniCloudRequestId() console.log('请求ID:', requestId) ``` -------------------------------- ### VK-UniCloud Framework Overview Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-permission-system.md Provides an overview of the VK-UniCloud framework, including its core features and project structure. ```APIDOC ## VK-UniCloud Framework Overview VK-UniCloud is a rapid development framework based on UniCloud. It consists of two main parts: - **Client-side Framework**: `vk-unicloud-router` - A cloud function routing mode development framework. - **Management-side Framework**: `vk-unicloud-admin` - A backend management system based on Element UI. ### Core Features - **Cloud Function Routing Mode**: Implemented with pure native code for strong compatibility, reducing the number of cloud functions and supporting both cloud function and cloud object modes. It also enhances cloud function request logging for easier debugging. - **Rich Built-in APIs**: Integrates uni-id user system, provides `vk.baseDao` database API, includes backend APIs for platforms like WeChat and Alipay, and supports features like SMS, email, and payments. - **Permission Management**: Features global filters for illegal requests, a comprehensive user role permission system, and allows permissions to be precisely defined for each cloud function. - **Development Tools**: Includes versatile table and form components for the management side, a code generator, and debugging tools. ## Project Structure ### Cloud Directory Structure ``` uniCloud-alipay/ ├── cloudfunctions/ # Cloud functions directory │ ├── common/ # Common modules │ │ ├── uni-config-center/ # Configuration center │ │ ├── uni-id/ # User identity management │ │ └── vk-unicloud/ # VK framework core │ └── router/ # Routing cloud function │ ├── service/ # Business logic │ │ ├── admin/ # Management side logic │ │ ├── client/ # Client-side logic │ │ └── user/ # User center │ └── index.js # Entry file ├── database/ # Database Schema │ ├── uni-id-users.schema.json │ └── custom-table.schema.json └── cloudobjects/ # Cloud objects directory (optional) ``` ### Cloud Function Directory Permission Specification ``` service/ ├── admin/ # Management side business logic │ └── [module]/ │ ├── sys/ # Requires specific permission verification │ ├── kh/ # Requires login + allow_login_background │ └── pub/ # Public access ├── client/ # Client-side business logic │ └── [module]/ │ ├── kh/ # Requires login │ └── pub/ # Public access └── user/ # User center service ├── sys/ # Administrator permissions ├── kh/ # User login permissions └── pub/ # Public access ``` ``` -------------------------------- ### Vuex Full API Usage Source: https://github.com/382444017/vk-unicloud/blob/master/frontend-state-management.md Illustrates the complete API for Vuex interactions, including getting state, setting state, accessing getters with and without parameters, committing mutations, and dispatching actions. This provides more granular control over the Vuex store. ```javascript // 获取数据 const userInfo = vk.vuex.get('$user.userInfo') // 设置数据 vk.vuex.set('$user.userInfo.avatar', newAvatar) // 获取 getters const userInfo = vk.vuex.getters('$user/getUserInfo') const permission = vk.vuex.getters('$user/getUserPermission', 'user-manage') // 提交 mutations vk.vuex.commit('$user/setUserInfo', userInfo) // 触发 actions vk.vuex.dispatch('$user/fetchUserInfo') ``` -------------------------------- ### 获取工具包 (this.getUtil) Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-object-development.md 此API用于获取一个包含多种实用工具的对象,如customUtil、uniID、config、pubFun、v极速开发、db等。这些工具可以简化开发过程,提供封装好的常用功能。 ```javascript module.exports = { _before: async function() { let { customUtil, uniID, config, pubFun, v极速开发, db, _, $ } = this.getUtil(); // 使用工具包 } } ``` -------------------------------- ### Manage and Clear Global Parameters in VK Unicloud (JavaScript) Source: https://github.com/382444017/vk-unicloud/blob/master/frontend-global-params.md Provides examples of managing global parameters, including dynamically switching the shop ID using `vk.setCustomClientInfo` or `vk.callFunctionUtil.updateRequestGlobalParam`, and clearing all global parameters by calling `vk.setCustomClientInfo({})` with an empty object. ```javascript // 动态切换店铺 const switchShop = (shopId) => { vk.setCustomClientInfo({ shop_id: shopId }) // 或者使用方式二 vk.callFunctionUtil.updateRequestGlobalParam({ "shop-manage": { regExp: "^shop/kh/", data: { shop_id: shopId } } }) } // 清除全局参数 vk.setCustomClientInfo({}) ``` -------------------------------- ### Set and Get Global Client Info in VK Unicloud (JavaScript) Source: https://github.com/382444017/vk-unicloud/blob/master/frontend-global-params.md Demonstrates how to set global client information using `vk.setCustomClientInfo` and how to retrieve it within a cloud function or cloud object. This method is recommended for separating parameters from business data. ```javascript // 设置全局参数 vk.setCustomClientInfo({ shop_id: "001", tenant_id: "tenant_001" }) // 云函数中获取(云函数) const customClientInfo = originalParam.context.customInfo console.log('店铺ID:', customClientInfo.shop_id) // 云对象中获取 const customClientInfo = this.getCustomClientInfo() console.log('店铺ID:', customClientInfo.shop_id) ``` -------------------------------- ### 获取临时下载链接 (JavaScript) Source: https://github.com/382444017/vk-unicloud/blob/master/cloud-ext-storage-basic.md 为指定的文件列表生成临时的下载链接。可以设置链接的有效期。 ```javascript let res = await extStorageManager.getTempFileURL({ fileList: ["qiniu://test.jpg"], // 文件地址列表 expiresIn: 3600 // 有效期(秒) }); ``` -------------------------------- ### VK-UniCloud 管理端项目结构 Source: https://github.com/382444017/vk-unicloud/blob/master/admin-framework-overview.md 展示了VK-UniCloud管理端特有的目录结构,包括页面文件、组件、静态资源、工具函数,以及页面模板(list, add, edit)和菜单配置(menu.json, menu-dev.json)。 ```text 管理端/ ├── src/ │ ├── pages/ # 页面文件 │ ├── components/ # 组件文件 │ ├── static/ # 静态资源 │ └── utils/ # 工具函数 ├── pages_template/ # 页面模板 (管理端特有) │ ├── components/ # 模板组件 │ ├── list/ # 列表页模板 │ ├── add/ # 新增页模板 │ └── edit/ # 编辑页模板 ├── static_menu/ # 菜单配置 (管理端特有) │ ├── menu.json # 生产环境菜单 │ └── menu-dev.json # 开发环境菜单 ├── pages.json # 页面配置 └── pages-dev.json # 开发页面配置 ``` -------------------------------- ### JavaScript 登录状态管理(Vuex) Source: https://github.com/382444017/vk-unicloud/blob/master/frontend-best-practices.md 提供了处理用户登录和登出状态的 JavaScript 函数。包括使用 `vk.setVuex` 和 `vk.getVuex` 来操作 Vuex store 中的用户信息、token 和登录状态,以及导航到登录页。 ```javascript // 登录成功后设置用户数据 const handleLoginSuccess = (userInfo, token) => { vk.setVuex('$user.userInfo', userInfo) vk.setVuex('$user.token', token) vk.setVuex('极狐user.loginStatus', true) } // 登出清除数据 const handleLogout = () => { vk.vuex.commit('$user/clearUserData') // 跳转到登录页 vk.navigateToLogin() } // 检查登录状态 const checkLoginStatus = () => { const loginStatus = vk.getVuex('$user.loginStatus') const token = vk.getVuex('$user.token') return loginStatus && token } ``` -------------------------------- ### Update Request Global Params with RegExp in VK Unicloud (JavaScript) Source: https://github.com/382444017/vk-unicloud/blob/master/frontend-global-params.md Shows how to configure global request parameters using `vk.callFunctionUtil.updateRequestGlobalParam`, which allows defining parameters based on regular expression matching for different routes. It also includes an example of manually specifying a configuration for a function call. ```javascript // 设置全局参数 vk.callFunctionUtil.updateRequestGlobalParam({ "shop-manage": { regExp: "^shop/kh/", // 正则表达式匹配 data: { shop_id: "001" } }, "user-manage": { regExp: ["^user/kh/", "^member/kh/"], // 支持多个正则 data: { tenant_id: "tenant_001" } } }) // 手动指定使用某个配置 vk.callFunction({ url: 'other/api/getData', globalParamName: "shop-manage", // 手动指定配置 data: { keyword: "test" } }) ``` -------------------------------- ### JSON: 菜单配置文件 Source: https://github.com/382444017/vk-unicloud/blob/master/frontend-admin-rules.md 定义了管理端应用的菜单结构和权限。`static_menu/menu.json`文件采用JSON格式,包含菜单的ID、名称、图标、排序、URL和权限标识。支持多级菜单嵌套,`permission`字段用于前端路由权限控制。 ```json // static_menu/menu.json { "list": [ { "menu_id": "system", "name": "系统管理", "icon": "el-icon-setting", "sort": 1, "children": [ { "menu_id": "system.user", "name": "用户管理", "url": "/pages/system/user/list", "icon": "el-icon-user", "sort": 1, "permission": "user:view" }, { "menu_id": "system.role", "name": "角色管理", "url": "/pages/system/role/list", "icon": "el-icon-s-custom", "sort": 2, "permission": "role:view" }, { "menu_id": "system.menu", "name": "菜单管理", "url": "/pages/system/menu/list", "icon": "el-icon-menu", "sort": 3, "permission": "menu:view" } ] }, { "menu_id": "content", "name": "内容管理", "icon": "el-icon-document", "sort": 2, "children": [ { "menu_id": "content.article", "name": "文章管理", "url": "/pages/content/article/list", "icon": "el-icon-edit", "sort": 1, "permission": "article:view" } ] } ] } ``` -------------------------------- ### Common Form Field Configurations for VK-Data-Form Source: https://github.com/382444017/vk-unicloud/blob/master/admin-form-component.md Provides examples of common field type configurations for the VK-Data-Form component. This includes settings for text input, number input, select dropdowns, radio buttons, image uploads, and rich text editors, showcasing key properties like `key`, `title`, `type`, `placeholder`, `options`, `limit`, and `action`. ```javascript // 常用表单字段配置 const formColumns = [ // 文本输入 { key: "name", title: "姓名", type: "text", placeholder: "请输入姓名", maxlength: 50 }, // 数字输入 { key: "age", title: "年龄", type: "number", min: 0, max: 150 }, // 下拉选择 { key: "category", title: "分类", type: "select", options: [ { value: "1", text: "分类1" }, { value: "2", text: "分类2" } ] }, // 单选框 { key: "status", title: "状态", type: "radio", options: [ { value: 1, text: "启用" }, { value: 0, text: "禁用" } ] }, // 图片上传 { key: "avatar", title: "头像", type: "image", limit: 1, action: "upload", accept: "image/*" }, // 富文本编辑器 { key: "content", title: "内容", type: "editor", height: 300 } ] ``` -------------------------------- ### 多文件上传 (JavaScript) Source: https://github.com/382444017/vk-unicloud/blob/master/frontend-file-upload.md 演示了如何同时选择多个文件 (`uni.chooseImage` with `count: 9`) 并使用`Promise.all`并发上传。每个文件上传都配置了`cloudDirectory`,上传完成后会将所有文件的URL收集到`imageList`数组中。 ```javascript // 选择多个文件 uni.chooseImage({ count: 9, success: (res) => { const uploadPromises = res.tempFiles.map(file => { return vk.uploadFile({ file: file, cloudDirectory: "gallery" }) }) // 并发上传 Promise.all(uploadPromises) .then(results => { console.log('所有文件上传完成:', results) this.imageList = results.map(item => item.url) }) .catch(err => { console.error('上传失败:', err) }) } }) ```