### RegExp Parameter Usage
Source: https://vkdoc.fsq.pub/client/uniCloud/middleware/filter
Explains how to use the `regExp` parameter for matching various URL patterns, including single string rules, array rules, and common examples.
```APIDOC
## regExp Parameter Description
- If `regExp` is a string, it represents a single matching condition.
- If `regExp` is an array, any rule within the array matching will trigger the middleware.
**Common RegExp Examples:**
- Match all: `"(.*)"`
- Match paths starting with `xxx/kh`: `"^xxx/kh"`
- Match paths ending with `xxx`: `"xxx$"`
- Exact match for `xxx/kh/getList`: `"^xxx/kh/getList$"`
- Multiple exact matches for `xxx/kh/getList` and `xxx/kh/add`:
```json
[
"^xxx/kh/getList$",
"^xxx/kh/add$"
]
```
```
--------------------------------
### Custom Filter Code Example (Single Store Version)
Source: https://vkdoc.fsq.pub/client/uniCloud/middleware/filter
Provides a practical code example for creating a custom filter (`shopManage`) to manage shop permissions in a single-store backend system.
```APIDOC
## Custom Filter Code Example (Single Store Version)
```javascript
/**
* Shop permission filter example
*/
module.exports = [
{
id: "shopManage",
regExp: "^client/shop/manage/(.*)",
description: "Shop operation interfaces require permission checks",
index: 310, // Must be > 300, as the user login check filter has an index of 200 (sys is 300). Values closer to 0 execute first.
mode: "onActionExecuting",
enable: true, // Set enable = false to disable this middleware
main: async function(event) {
let { util, filterResponse } = event;
let { vk, db, _ } = util;
let { uid, userInfo = {} } = filterResponse;
if (vk.pubfn.isNull(userInfo) && uid) {
// If userInfo is empty, fetch user info by uid (kh type cloud objects might have empty userInfo by default)
userInfo = await vk.daoCenter.userDao.findById(uid);
filterResponse.userInfo = userInfo; // Update filterResponse for easier access in cloud functions
}
let { role = [] } = userInfo;
let res = { code: 0, msg: 'ok' };
// Intercept if the user does not have the 'shopManage' role
if (role.indexOf("shopManage") === -1) {
return { code: -1, msg: 'No permission' };
}
return res;
}
}
]
```
```
--------------------------------
### Initialize uniCloud Database and Commands
Source: https://vkdoc.fsq.pub/client/uniCloud/db/question
This snippet shows how to get a global database reference and assign database command operators for use in uniCloud functions. It defines variables for the database, command operator, and aggregate operator.
```javascript
var db = uniCloud.database(); // 全局数据库引用
var _ = db.command; // 数据库操作符
var $ = _.aggregate; // 聚合查询操作符
```
--------------------------------
### Execute Lua Script
Source: https://vkdoc.fsq.pub/vk-redis/api
This endpoint demonstrates how to execute a Lua script on Redis. It allows for complex atomic operations by using the `EVAL` command. The example script checks a key, sets it if it doesn't exist, increments it if it's less than 10, or does nothing if it's 10 or greater.
```APIDOC
## POST /redis/eval
### Description
Executes a Lua script on the Redis server for atomic operations.
### Method
POST
### Endpoint
/redis/eval
### Parameters
#### Request Body
- **script** (string) - Required - The Lua script to execute.
- **keys** (array of strings) - Optional - Keys that the script will access.
- **args** (array of strings) - Optional - Arguments to pass to the script.
### Request Example
```json
{
"script": "local val = redis.call('get','key-test'); local valNum = tonumber(val); if (valNum == nil) then redis.call('set', 'key-test', 1); return {0, 1}; end if (valNum < 10) then redis.call('incrby', 'key-test', 1); return {1, valNum + 1}; else return {2, valNum}; end",
"keys": ["key-test"],
"args": []
}
```
### Response
#### Success Response (200)
- **result** (array) - The result of the Lua script execution. The structure depends on the script's return value.
#### Response Example
```json
{
"result": [0, 1]
}
```
```
--------------------------------
### Dynamic Right Button Visibility (JavaScript)
Source: https://vkdoc.fsq.pub/admin/components/24%E3%80%81array
Dynamically controls the visibility of 'copy' and 'delete' buttons based on a provided condition. The example hides the first row's buttons.
```javascript
rightBtns: [
{
mode: 'copy',
title: '复制',
show: (item, index) => {
// 第一1个不显示
return index > 0;
}
},
{
mode: 'delete',
title: '删除',
show: (item, index) => {
// 第一1个不显示
return index > 0;
}
}
]
```
--------------------------------
### Implement a Percentage Input with vk-data-input in Vue
Source: https://vkdoc.fsq.pub/admin/4/codeTips
This snippet shows how to use vk-data-input as a percentage input field. It binds the input value to `form1.value` and sets the width and placeholder. The `precision` prop is set to 0 in the example.
```vue
{
"vk-data-input(百分比输入框)": {
"body": [
""
],
"prefix": "vk-data-input",
"project": "uni-app",
"scope": "source.vue.html"
}
}
```
--------------------------------
### Vue.js Data Structure for Form Validation Rules
Source: https://vkdoc.fsq.pub/admin/3/form
Illustrates the data structure for defining form validation rules within a Vue component's data function. It includes examples for required fields, type checking, and custom validators using a utility function `vk.pubfn.validator`.
```javascript
data: function() {
return {
form1: {
data: {
},
props: {
rules: {
user_id: [
{ required: true, message: "用户ID不能为空", trigger: ['blur', 'change'] }
],
money: [
{ required: true, message: "金额不能为空", trigger: ['blur', 'change'] },
{ type: "number", message: "金额必须是数字", trigger: ['blur', 'change'] }
],
mobile: [
{ required: true, message: '提现人手机号不能为空', trigger: ['blur', 'change'] },
{ validator: vk.pubfn.validator("mobile"), message: '手机号格式错误', trigger: 'blur' }
],
mobileCode: [
{ required: true, message: '验证码不能为空', trigger: ['blur', 'change'] },
{ validator: vk.pubfn.validator("mobileCode"), message: '验证码格式错误', trigger: 'blur' }
],
username: [
{ required: true, message: '用户名不能为空', trigger: ['blur', 'change'] },
{
validator: vk.pubfn.validator("username"),
message: '用户名以字母开头,长度在3~32之间,只能包含字母、数字和下划线',
trigger: 'blur'
}
],
password: [
{ required: true, message: '密码不能为空', trigger: ['blur', 'change'] },
{
validator: vk.pubfn.validator("password"),
message: '密码长度在6~18之间,只能包含字母、数字和下划线',
trigger: 'blur'
}
],
password2: [
{ required: true, message: '密码不能为空', trigger: ['blur', 'change'] },
{
validator: (rule, value, callback) => {
if (value === '') {
callback(new Error('请再次输入密码'));
} else if (value !== that.form1.data.password) {
callback(new Error('两次输入密码不一致!'));
} else {
callback();
}
},
trigger: ['blur', 'change']
}
],
nickname: [
{ required: true, message: '昵称为必填字段', trigger: ['blur', 'change'] },
{ min: 2, max: 20, message: '昵称长度在 2 到 20 之间', trigger: 'blur' }
],
card: [
{ validator: vk.pubfn.validator("card"), message: '身份证格式错误', trigger: 'blur' }
],
payPwd: [
{ validator: vk.pubfn.validator("payPwd"), message: '支付密码必须为 6位纯数字', trigger: 'blur' }
],
postal: [
{ validator: vk.pubfn.validator("postal"), message: '邮政编码格式错误', trigger: 'blur' }
],
email: [
{ validator: vk.pubfn.validator("email"), message: '邮箱格式错误', trigger: 'blur' }
],
QQ: [
{ validator: vk.pubfn.validator("QQ"), message: 'QQ号格式错误', trigger: 'blur' }
],
URL: [
{ validator: vk.pubfn.validator("URL"), message: 'URL格式错误', trigger: 'blur' }
],
IP: [
{ validator: vk.pubfn.validator("IP"), message: 'IP格式错误', trigger: 'blur' }
],
date: [
{ validator: vk.pubfn.validator("date"), message: 'date格式错误', trigger: 'blur' }
],
time: [
{ validator: vk.pubfn.validator("time"), message: 'time格式错误', trigger: 'blur' }
],
dateTime: [
{ validator: vk.pubfn.validator("dateTime"), message: 'dateTime格式错误', trigger: 'blur' }
],
english: [
{ validator: vk.pubfn.validator("english"), message: '只能输入英文', trigger: 'blur' }
],
englishnumber: [
{ validator: vk.pubfn.validator("english+number"), message: '只能输入英文或数字', trigger: 'blur' }
],
englishnumber2: [
{ validator: vk.pubfn.validator("english+number+_"), message: '只能输入英文、数字、下划线', trigger: 'blur' }
],
chinese: [
{ validator: vk.pubfn.validator("chinese"), message: '只能输入中文', trigger: 'blur' }
],
lower: [
{ validator: vk.pubfn.validator("lower"), message: '只能输入小写字母', trigger: 'blur' }
],
upper: [
{ validator: vk.pubfn.validator("upper"), message: '只能输入大写字母',
trigger: 'blur'
}
]
}
}
}
}
}
```
--------------------------------
### Get Object Property Data with $getData in Vue
Source: https://vkdoc.fsq.pub/admin/4/codeTips
This snippet defines a function `$getData` to safely access nested properties within a data object. It takes the data object, a key path (e.g., 'aa.aa'), and a default value as input. If the property exists, it returns the value; otherwise, it returns the default value. It's designed to prevent errors when accessing potentially undefined properties.
```vue
{
"$getData(data,key,defaultValue)": {
"prefix": "$getData",
"body": [
"$getData(data, 'aa.aa', defaultValue)"
],
"triggerAssist": false,
"description": "智能获取对象属性数据"
}
}
```
--------------------------------
### 示例:单店版店铺权限过滤器 - JavaScript
Source: https://vkdoc.fsq.pub/client/uniCloud/middleware/filter
演示了如何使用 JavaScript 编写一个自定义过滤器,用于检查用户是否有权限操作特定店铺。该过滤器在操作执行前执行,如果用户没有 'shopManage' 角色,则会返回权限不足的错误。
```javascript
/**
* 店铺权限过滤器示例
*/
module.exports = [
{
id: "shopManage",
regExp: "^client/shop/manage/(.*)",
description: "店铺操作接口需要检测用户是否有权限",
index: 310,
mode:"onActionExecuting",
enable:true,
main: async function(event) {
let { util, filterResponse } = event;
let { vk , db, _ } = util;
let { uid, userInfo = {} } = filterResponse;
if (vk.pubfn.isNull(userInfo) && uid) {
userInfo = await vk.daoCenter.userDao.findById(uid);
filterResponse.userInfo = userInfo;
}
let { role = [] } = userInfo;
let res = { code : 0, msg : 'ok' };
if(role.indexOf("shopManage") === -1){
return { code : -1, msg : '无权限' };
}
return res;
}
}
]
```
--------------------------------
### Middleware Parameter Configuration
Source: https://vkdoc.fsq.pub/client/uniCloud/middleware/filter
Details on the parameters available for configuring middleware (filters), including ID, RegExp, description, index, mode, enable, main function, and returnMode.
```APIDOC
## Middleware Parameter Description
| Parameter | Description | Type | Default | Options |
|---|---|---|---|---|
| id | Middleware ID, must be unique globally. | String | - | - |
| regExp | Regular expression matching rules (supports array). | String Array | None | - |
| description | Middleware description for reference. | String | - | - |
| index | Middleware execution order (smaller value executes first). | Number | - | - |
| mode | Middleware mode. | String | onActionExecuting | See mode parameter description below. |
| enable | Whether to enable the middleware. | Boolean | false | true |
| main | The function to execute. | async function(event, serviceRes) | - | - |
| returnMode | Return value mode, only effective when mode is `onActionExecuted`. | Number | 0 | 1 |
```
--------------------------------
### RegExp 精确匹配 xxx/kh/getList - JavaScript
Source: https://vkdoc.fsq.pub/client/uniCloud/middleware/filter
使用 JavaScript 中的 RegExp 对象精确匹配指定的字符串。常用于设置中间件的精确路径匹配规则。
```javascript
regExp: "^xxx/kh/getList$"
```
--------------------------------
### Mode Parameter Options
Source: https://vkdoc.fsq.pub/client/uniCloud/middleware/filter
Details the different modes available for middleware execution, specifying when the middleware logic should be applied relative to the action's lifecycle.
```APIDOC
## Mode Parameter Description
| Type | Description |
|---|---|
| onActionExecuting | Executes before the action. |
| onActionExecuted | Executes after the action. |
| onActionIntercepted | Executes after the action is intercepted by another middleware. |
| onActionError | Executes when the action execution results in an error. |
```
--------------------------------
### RegExp 匹配所有 - JavaScript
Source: https://vkdoc.fsq.pub/client/uniCloud/middleware/filter
使用 JavaScript 中的 RegExp 对象匹配所有字符串。常用于设置中间件的全局匹配规则。
```javascript
regExp: "(.*)"
```
--------------------------------
### 主题配置文件 index.js 引入新主题
Source: https://vkdoc.fsq.pub/admin/1/theme
在 `/common/theme/index.js` 文件中引入新的自定义主题文件(如 'aaa.js'),以便在 `app.config.js` 中使用。
```javascript
import white from './white.js'
import black from './black.js'
import blackWhite from './blackWhite.js'
import aaa from './aaa.js'
export default {
white,
black,
blackWhite,
aaa
};
```
--------------------------------
### vk-admin 主题配置示例
Source: https://vkdoc.fsq.pub/admin/1/theme
在 app.config.js 文件中配置主题,可以设置当前使用的主题(如 'blackWhite'),并可以定义自定义主题的样式。
```javascript
theme: {
// 当前使用哪个主题
use: "blackWhite", // white blackWhite black custom
...themeConfig,
// 自定义主题
custom: {
// 左侧菜单样式
leftMenu: {
backgroundColor: "", // 背景色
subBackgroundColor: "", // 子菜单背景色
textColor: "", // 菜单文字颜色
activeTextColor: "", // 菜单被选中时的文字颜色
activeBackgroundColor: "", // 菜单被选中时的背景颜色
collapseActiveTextColor: "", // 菜单折叠时选中时的文字颜色
collapseActiveBackgroundColor: "", // 菜单折叠时选中时的背景颜色
hoverTextColor: "", // 菜单hover时的文字颜色
hoverBackgroundColor: "", // 菜单hover时的背景颜色
boxShadow: "", // 菜单右边框的阴影
borderTop: "", // 菜单顶部的边框
},
// 顶部菜单样式
topMenu: {
backgroundColor: "", // 顶部背景颜色
textColor: "", // 顶部文字颜色
}
}
}
```
--------------------------------
### RegExp 匹配多个路径 - JavaScript
Source: https://vkdoc.fsq.pub/client/uniCloud/middleware/filter
使用 JavaScript 中的 RegExp 对象匹配多个指定的字符串。常用于设置中间件的多个路径匹配规则,只要其中一个匹配即可。
```javascript
regExp: [
"^xxx/kh/getList$",
"^xxx/kh/add$"
]
```
--------------------------------
### RegExp 匹配 xxx 结尾 - JavaScript
Source: https://vkdoc.fsq.pub/client/uniCloud/middleware/filter
使用 JavaScript 中的 RegExp 对象匹配以特定字符串结尾的字符串。常用于设置中间件的路径匹配规则。
```javascript
regExp: "xxx$"
```
--------------------------------
### UI Component: Image Preview Configuration
Source: https://vkdoc.fsq.pub/admin/components/18%E3%80%81image
Configures an image upload component to provide a preview functionality. The `onPreview` callback allows custom handling of the preview event, directly opening the file's URL in a preview modal when a file is clicked.
```javascript
{
key: "image1", title: "image类型", type: "image", limit: 9, cloudPathRemoveChinese: true,
onPreview: (file, open) => {
// 主动调用open函数打开预览弹窗
open(file.url);
}
},
```
--------------------------------
### vk-admin 引入主题配置文件
Source: https://vkdoc.fsq.pub/admin/1/theme
在 app.config.js 文件中引入主题配置文件,这是使用自定义主题的第一步。
```javascript
import themeConfig from '@/common/theme/index.js'
```
--------------------------------
### RegExp 匹配以 xxx/kh 开头 - JavaScript
Source: https://vkdoc.fsq.pub/client/uniCloud/middleware/filter
使用 JavaScript 中的 RegExp 对象匹配以特定字符串开头的字符串。常用于设置中间件的路径匹配规则。
```javascript
regExp: "^xxx/kh"
```
--------------------------------
### ReturnMode Parameter Options
Source: https://vkdoc.fsq.pub/client/uniCloud/middleware/filter
Explains the `returnMode` parameter, which affects how middleware return values are combined with action return values when the mode is `onActionExecuted`.
```APIDOC
## returnMode Parameter Description
Only effective when `mode` is `onActionExecuted`.
| Value | Description |
|---|---|
| 0 | Uses `Object.assign` for merging return values. |
| 1 | Completely replaces the action's return value with the middleware's return value. |
**Detailed Explanation:**
- **`returnMode: 0` (Merge):** Combines return values using `Object.assign`. If the action returns `{ "code": 0, "a": 1 }` and the middleware returns `{ "code": -1, "msg": "Failed" }`, the final result is `{ "code": -1, "msg": "Failed", "a": 1 }`.
- **`returnMode: 1` (Replace):** The middleware's return value completely replaces the action's return value. If the action returns `{ "code": 0, "a": 1 }` and the middleware returns `{ "code": -1, "msg": "Failed" }`, the final result is `{ "code": -1, "msg": "Failed" }`.
```
--------------------------------
### POST /presentCurrency (代币赠送)
Source: https://vkdoc.fsq.pub/vk-uni-pay/wxpay-virtual
Allows for the presentation of virtual currency to users. This API is used to gift digital currency to a user's account.
```APIDOC
## POST /presentCurrency
### Description
Allows for the presentation of virtual currency to users. This API is used to gift digital currency to a user's account.
### Method
POST
### Endpoint
/presentCurrency
### Parameters
#### Request Body
- **openid** (String) - Required - The user's openid.
- **userIp** (String) - Required - The user's IP address.
- **amount** (Number) - Required - The amount of currency to present.
- **outTradeNo** (String) - Required - The unique order number for the transaction.
- **deviceType** (Number) - Required - The platform type (1 for Android, 2 for Apple).
### Request Example
```json
{
"openid": "user_openid",
"userIp": "192.168.1.1",
"amount": 100,
"outTradeNo": "ORDER12345",
"deviceType": 1
}
```
### Response
#### Success Response (200)
- **balance** (String) - The user's updated currency balance after the presentation.
- **presentBalance** (String) - The total amount of currency the user received as a gift.
- **outTradeNo** (String) - The transaction order number.
#### Response Example
```json
{
"balance": "1000",
"presentBalance": "100",
"outTradeNo": "ORDER12345"
}
```
```
--------------------------------
### Define Development-Only Pages (pages-dev.json)
Source: https://vkdoc.fsq.pub/client/question/q6
This JSON file lists pages that should only be included in the build when the environment is set to development. It uses HBuilderX's sub-package structure to define the root directory and the pages within it.
```json
{
"subPackages": [{
"root": "pages_template",
"pages": [{
"path": "db-test/db-test",
"style": {
"navigationBarTitleText": "数据库调用示例"
}
},
{
"path": "db-test/list/list",
"style": {
"navigationBarTitleText": "列表渲染 - 分页加载"
}
},
{
"path": "uni-id/index/index",
"style": {
"navigationBarTitleText": "云函数调用示例-uni-id"
}
},
{
"path": "uni-id/password/password",
"style": {}
},
{
"path": "uni-id/mobile/mobile",
"style": {}
},
{
"path": "uni-id/univerify/univerify",
"style": {}
},
{
"path": "uni-id/weixin/weixin",
"style": {}
},
{
"path": "uni-id/alipay/alipay",
"style": {}
},
{
"path": "uni-id/util/util",
"style": {}
},
{
"path": "uni-id/email/email",
"style": {}
},
{
"path": "uni-id/login/index/index",
"style": {
"navigationBarTitleText": "登录"
}
},
{
"path": "uni-id/login/register/register",
"style": {
"navigationBarTitleText": "注册"
}
},
{
"path": "uni-id/login/forget/forget",
"style": {
"navigationBarTitleText": "找回密码"
}
},
{
"path": "vk-vuex/vk-vuex",
"style": {
"navigationBarTitleText": "vuex演示示例"
}
},
{
"path": "openapi/weixin/weixin",
"style": {}
},
{
"path": "openapi/weixin/msgSecCheck/msgSecCheck",
"style": {}
},
{
"path": "openapi/weixin/imgSecCheck/imgSecCheck",
"style": {}
},
{
"path": "openapi/weixin/sendMessage/sendMessage",
"style": {}
},
{
"path": "openapi/baidu/baidu",
"style": {}
}]
}]
}
```
--------------------------------
### Present Virtual Currency using vk-uni-pay (JavaScript)
Source: https://vkdoc.fsq.pub/vk-uni-pay/wxpay-virtual
This JavaScript code snippet demonstrates how to use the 'presentCurrency' function from the vk-uni-pay module to gift virtual currency to a user. It requires user identification (openid, userIp), transaction details (amount, outTradeNo), and device information. The function returns the updated user balance and gifting details.
```javascript
// 引入 vk-uni-pay 公共模块
const vkPay = require("vk-uni-pay");
exports.main = async (event, context) => {
let openid = ""; // 用户的openid
let userIp = ""; // 用户的ip地址
let out_trade_no = ""; // 商户订单号
let amount = 1; // 赠送代币数量
// 获取微信虚拟支付实例
const wxpayVirtualManager = await vkPay.getWxpayVirtualManager();
// 赠送代币
let res = await wxpayVirtualManager.presentCurrency({
openid, // 用户的openid
userIp, // 用户的ip地址
amount: Number(amount), // 赠送代币数量
outTradeNo: out_trade_no, // 商户订单号
deviceType: 1, // 平台类型1-安卓 仅支持传1
});
console.log('res: ', res);
return res;
};
```
--------------------------------
### 自定义主题 (黑白主题) 示例
Source: https://vkdoc.fsq.pub/admin/1/theme
定义一个名为 'aaa.js' 的自定义主题文件,配置左侧菜单和顶部菜单的样式,例如黑白主题的效果。
```javascript
// 黑白主题(左侧菜单黑,顶部白)
export default {
// 左侧菜单样式
leftMenu: {
backgroundColor: "#191a23",
subBackgroundColor:"#101117",
textColor: "rgba(255,255,255,0.8)",
activeTextColor: "#ffffff",
activeBackgroundColor: "#2d8cf0",
collapseActiveTextColor:"#2d8cf0",
collapseActiveBackgroundColor: "#2c3239",
hoverTextColor: "#ffffff",
hoverBackgroundColor: "#545f6c",
boxShadow: "2px 0 4px rgba(0,21,4,0.25)",
},
// 顶部菜单样式
topMenu: {
backgroundColor: "#ffffff", // 顶部背景颜色
textColor: "#999999", // 顶部文字颜色
}
}
```
--------------------------------
### Understanding Filters and Middleware
Source: https://vkdoc.fsq.pub/client/uniCloud/middleware/filter
Filters, also known as middleware, allow for intercepting requests before or after business cloud functions are executed. They can be used for various purposes like authentication, authorization, and data transformation.
```APIDOC
## Middleware (Filters)
Filters can intercept requests before or after business cloud functions execute, allowing for unified filtering and processing.
**Use Cases:**
- Intercepting logged-in users in e-commerce backends.
- Checking user permissions for specific shops.
- Passing shop information directly to business cloud functions.
- Accessing shop information within the `filterResponse` variable in cloud functions.
```
--------------------------------
### Conditional Page Merging Logic (pages.js)
Source: https://vkdoc.fsq.pub/client/question/q6
This JavaScript file dynamically includes pages defined in `pages-dev.json` into the main `pages.json` configuration, but only when the application is running in a development environment (NODE_ENV is not 'production'). It includes error handling for malformed JSON files.
```javascript
const debug = process.env.NODE_ENV !== 'production';
var devPages;
try {
// 只在开发环境中才会被HBX打包的页面
devPages = require('./pages-dev.json');
} catch (err) {
console.error("检测到pages-dev.json文件异常,请检查(json文件内不可以有注释,每个{}是否全部对配,是否多写了逗号,)");
console.error(err);
console.error("检测到pages-dev.json文件异常,请检查(json文件内不可以有注释,每个{}是否全部对配,是否多写了逗号,)");
throw Error(err)
}
module.exports = function(pagesJson) {
try {
let newDevPages = JSON.parse(JSON.stringify(devPages));
if (debug && newDevPages) {
for (let keyName in newDevPages) {
let item = newDevPages[keyName];
if (Object.prototype.toString.call(item) === "[object Array]") {
pagesJson[keyName].push(...item);
} else if (Object.prototype.toString.call(item) === '[object Object]') {
pagesJson[keyName] = Object.assign(pagesJson[keyName], item);
}
}
}
} catch (err) {
console.error("pages.js运行异常,请检查");
console.error(err);
console.error("pages.js运行异常,请检查");
throw Error(err)
}
return pagesJson;
}
```
--------------------------------
### 自定义组件使用方式示例
Source: https://vkdoc.fsq.pub/admin/custom-components/custom-components
展示了如何在 vk-admin 的万能表格或万能表单中使用自定义组件。通过配置 `type` 为 `custom`,并指定 `component` 属性为自定义组件的名称(如 `custom-aaa`),即可引入和使用自定义组件。
```JavaScript
{ key:"key1", title:"我是自定义aaa组件", type:"custom", component:"custom-aaa" },
```
--------------------------------
### Implement a Discount Input with vk-data-input in Vue
Source: https://vkdoc.fsq.pub/admin/4/codeTips
This snippet shows how to implement a discount input field using the vk-data-input component. It binds the input value to `form1.value`, sets the width, and provides a placeholder. `precision` is set to 0.
```vue
{
"vk-data-input(折扣输入框)": {
"body": [
""
],
"prefix": "vk-data-input",
"project": "uni-app",
"scope": "source.vue.html"
}
}
```
--------------------------------
### Create a vk-data-table Component in Vue
Source: https://vkdoc.fsq.pub/admin/4/codeTips
This snippet creates a vk-data-table component with common configurations. It includes features like dynamic action and columns, query form parameters, pre-defined right buttons, row selection, row numbering, and pagination. It uses event handlers for update, delete, current page change, and selection change actions.
```vue
{
"vk-data-table(万能表格)": {
"body": [
"",
"",
""
],
"prefix": "vk-data-table",
"project": "uni-app",
"scope": "source.vue.html"
}
}
```
--------------------------------
### Vue 组件模板示例
Source: https://vkdoc.fsq.pub/admin/custom-components/custom-components
这是一个 Vue 组件的模板示例,用于 vk-admin 框架的“万能表单”、“万能表格”或“详情页”场景。它包含了组件的结构、props 定义(value, column, scene)以及一个输入事件处理方法 `_input`。
```Vue
{{ value }}
{{ value }}
```
--------------------------------
### Encrypt and Decrypt Data using AES in Java
Source: https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/crypto
Provides Java code for encrypting and decrypting strings using AES with a 256-bit key in ECB mode with PKCS5 padding. It handles key length and uses Base64 encoding for the encrypted output. Dependencies include Java's standard crypto libraries.
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class CryptoUtil {
// 调用示例
public static void main(String[] args) {
try {
String key = "12345678901234561234567890123456"; // 必须是固定的32位(只支持数字、英文)
String text = "{\"a\":1,\"b\":\"2\"}"; // 待加密的内容
// 加密
String encrypted = encrypt(text, key);
System.out.println("encrypted: " + encrypted);
} catch (Exception e) {
e.printStackTrace();
}
}
// 解密函数
private static String decrypt(String encryptedData, String key) throws Exception {
if (key.length() > 32) {
key = key.substring(0, 32);
}
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
// 加密函数
private static String encrypt(String data, String key) throws Exception {
if (key.length() > 32) {
key = key.substring(0, 32);
}
byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(dataBytes);
return Base64.getEncoder().encodeToString(encryptedBytes);
}
}
```
--------------------------------
### Create a Basic Dialog with vk-data-dialog in Vue
Source: https://vkdoc.fsq.pub/admin/4/codeTips
This snippet creates a simple vk-data-dialog for displaying custom content. It allows setting the title, width, and top position. It also features a footer slot with cancel and confirm buttons. Clicking outside the dialog closes it.
```vue
{
"vk-data-dialog(普通弹窗)": {
"body": [
"",
"",
" 这里是自定义内容${0}",
" ",
" 取 消",
" 确 定",
" ",
"",
""
],
"prefix": "vk-data-dialog",
"project": "uni-app",
"scope": "source.vue.html"
}
}
```
--------------------------------
### Implement a Number Box Input (Stepper) with vk-data-input in Vue
Source: https://vkdoc.fsq.pub/admin/4/codeTips
This snippet creates a number box (stepper) input field using vk-data-input. It binds the input value to `form1.value`, sets the width, and provides a placeholder. The `precision` prop controls the number of decimal places.
```vue
{
"vk-data-input(步进器)": {
"body": [
""
],
"prefix": "vk-data-input",
"project": "uni-app",
"scope": "source.vue.html"
}
}
```
--------------------------------
### Execute Lua Script for Conditional Key Operations
Source: https://vkdoc.fsq.pub/vk-redis/api
This JavaScript code snippet demonstrates executing a Lua script using the 'redis' client. The script checks if a key 'key-test' exists. If not, it sets the key to 1. If the key exists and its value is less than 10, it increments the value. Otherwise, it returns the current value without modification. This is useful for ensuring data consistency in concurrent environments.
```javascript
const [operationType, currentValue] = await redis.eval(`
local val = redis.call('get','key-test')
local valNum = tonumber(val)
if (valNum == nil) then
redis.call('set', 'key-test', 1)
return {0, 1}
end
if (valNum < 10) then
redis.call('incrby', 'key-test', 1)
return {1, valNum + 1}
else
return {2, valNum}
end
`, 0)
```
--------------------------------
### Cloud Function: Download and Decrypt File
Source: https://vkdoc.fsq.pub/admin/components/18%E3%80%81image
Downloads an encrypted file from cloud storage using its URL, converts the buffer to a string, decrypts it using AES-256-ECB, and returns the original base64 encoded file content. Includes a permission check for administrators.
```javascript
'use strict';
module.exports = {
/**
* 解密文件
*/
main: async (event) => {
let { data = {}, userInfo, util, filterResponse, originalParam } = event;
let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
let { uid } = data;
let res = { code: 0, msg: "" };
// 业务逻辑开始-----------------------------------------------------------
let id_card_front = "加密文件的url";
// 此处应该判断下该用户是否有权限解密此文件
if (userInfo.role.indexOf("admin") === -1) {
return { code:-1, msg: "您没有权限访问" };
}
// 下载图片
let imageBuffer = await vk.request({
url: id_card_front,
method: "GET",
dataType: "default"
});
// 将imageBuffer转待解密的字符串
let decrypt = imageBuffer.toString('utf8');
// 解密得到真实的图片base64
let id_card_front_base64 = vk.crypto.aes.decrypt({
mode: "aes-256-ecb",
data: decrypt
});
// 返回给前端解密后的文件的base64
res.base64 = id_card_front_base64
// 业务逻辑结束-----------------------------------------------------------
return res;
}
}
```
--------------------------------
### Display an Icon Using vk-data-icon in Vue
Source: https://vkdoc.fsq.pub/admin/4/codeTips
This snippet demonstrates how to use the vk-data-icon component to display an icon. The `name` prop is used to specify the icon to display (e.g., 'vk-icon-text'), and the `size` prop controls the icon size.
```vue
{
"vk-data-icon(图标)": {
"body": [
""
],
"prefix": "vk-data-icon",
"project": "uni-app",
"scope": "source.vue.html"
}
}
```
--------------------------------
### Universal Form: Image Field Configuration
Source: https://vkdoc.fsq.pub/admin/components/18%E3%80%81image
Defines the configuration for an image field within a universal form component. It specifies the key, display title, data type ('image'), and the maximum number of files allowed, along with the display width in the table view.
```javascript
{ key: "image", title: "图片", type: "image", width: 120 },
```
--------------------------------
### Implement a Money Input with vk-data-input in Vue
Source: https://vkdoc.fsq.pub/admin/4/codeTips
This snippet demonstrates using vk-data-input for a money input field. It binds the input value to `form1.value` and sets the width and placeholder. The `precision` prop is set to 2 for displaying currency with two decimal places.
```vue
{
"vk-data-input(金额输入框)": {
"body": [
""
],
"prefix": "vk-data-input",
"project": "uni-app",
"scope": "source.vue.html"
}
}
```
--------------------------------
### Built-in Filters
Source: https://vkdoc.fsq.pub/client/uniCloud/middleware/filter
VK UI provides several built-in filters that are automatically enabled. You can override them by creating a custom filter with the same ID and a smaller index value.
```APIDOC
## Built-in Filters
- **pub:** Matches `/pub/`, allows all access.
- **kh:** Matches `/kh/`, validates user tokens and login status.
- **sys:** Matches `/sys/`, performs permission checks for cloud function execution.
```
--------------------------------
### Implement a Textarea Input with vk-data-input in Vue
Source: https://vkdoc.fsq.pub/admin/4/codeTips
This snippet demonstrates how to use vk-data-input as a textarea (multi-line text input). It binds the input value to `form1.value`, sets the width, and provides a placeholder.
```vue
{
"vk-data-input(多行文本)": {
"body": [
""
],
"prefix": "vk-data-input",
"project": "uni-app",
"scope": "source.vue.html"
}
}
```