### File Select Component Usage Examples
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-components/24-file-select-素材库选择.md
Examples demonstrating how to use the file-select component within different contexts, including direct configuration and integration with uni-app.
```APIDOC
## File Select Component Usage Examples
### Description
Examples demonstrating how to use the file-select component within different contexts, including direct configuration and integration with uni-app.
### Universal Form Usage
```js
{
key: "image1",
title: "Multiple Images",
type: "file-select",
placeholder: "Please select images",
fileType: "image",
multiple: true,
multipleLimit: 6,
imageFit: "cover"
}
```
### Universal Table Usage
```js
{
key: "image",
title: "Image",
type: "image",
width: 120
}
```
### Template Usage
```html
```
```
--------------------------------
### vk-data-detail Basic Usage Example
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-detail-examples.md
A fundamental example of using the vk-data-detail component to display user information. It demonstrates binding data and column configurations, along with setting a custom label width.
```vue
```
--------------------------------
### Install Context7 Tool
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/README.md
Command to install the Context7 command-line tool globally using npm. This tool is used for document retrieval and search within the project.
```bash
npm install -g context7
```
--------------------------------
### Upload Type Examples
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-upload-examples.md
Provides examples for different upload scenarios, including image uploads, document uploads, and multi-type file uploads.
```APIDOC
## Upload Type Examples
### Description
This section provides code examples for various upload types, demonstrating how to configure the `vk-data-upload` component for specific use cases like image uploads, document uploads, and handling multiple file types.
### Method
N/A (Component usage examples)
### Endpoint
N/A
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None (Component usage examples)
### Request Example
#### 1. Image Upload
```vue
```
#### 2. File Upload
```vue
点击上传
支持doc、docx、pdf、xls、xlsx格式
```
#### 3. Multi-Type File Upload
```vue
选择文件
```
#### 4. Custom Upload Handling
```vue
选择文件
开始上传
```
### Response
#### Success Response (N/A)
#### Response Example
N/A
```
--------------------------------
### Vuex Simplified API Usage (JavaScript)
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/frontend-state-management.md
Demonstrates the simplified API for interacting with Vuex state, including getting and setting data, with examples for direct property access and template usage.
```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') }}
```
--------------------------------
### Table Dialog Example
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-dialog-examples.md
Demonstrates displaying a table within a dialog for data visualization.
```APIDOC
## Table Dialog Example
### Description
This example shows how to embed a `vk-data-table` component inside a `vk-data-dialog` to display tabular data in a modal window.
### Method
N/A (Client-side component usage)
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
```vue
打开表格弹窗
```
### Response
#### Success Response (200)
N/A (Client-side component)
#### Response Example
N/A
```
--------------------------------
### vk-data-detail Multi-column Layout Example
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-detail-examples.md
Shows how to configure the vk-data-detail component for a multi-column layout, specifically two columns. This example binds product data and column configurations, adjusting the label width accordingly.
```vue
```
--------------------------------
### Basic Dialog Example
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-dialog-examples.md
Shows a simple dialog with custom content and confirmation/cancel buttons.
```APIDOC
## Basic Dialog Example
### Description
This example demonstrates how to use the `vk-data-dialog` component to display a basic modal window with a title, custom content, and confirmation/cancel actions.
### Method
N/A (Client-side component usage)
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
```vue
打开弹窗
这是弹窗内容区域
可以放置任何自定义内容
```
### Response
#### Success Response (200)
N/A (Client-side component)
#### Response Example
N/A
```
--------------------------------
### onChange Usage Example
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-components/10-remote-select-远程下拉.md
An example demonstrating how to use the `onChange` event handler for the remote select component.
```APIDOC
## onChange Usage Example
```js
{
key: "user_id",
title: "User Selector",
type: "remote-select",
placeholder: "Enter user account/nickname",
action: "admin/select/kh/user",
onChange: (val, formData, column, index, option) => {
console.log(1, val, formData, column, index, option);
}
}
```
**Note:** It is recommended to use `watch` instead of `onChange`. [Link to watch documentation](opens new window)
```
--------------------------------
### Field Configuration Examples
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-table-component.md
Examples of configuring fields for the table component, demonstrating different display options (detail only, row only, or none).
```APIDOC
## Field Configuration Examples
### Description
Examples of configuring fields for the table component, demonstrating different display options (detail only, row only, or none).
### Code Examples
```javascript
// Only display in detail popup
{ key: "nickname", title: "昵称", type: "text", show: ["detail"] }
// Only display in table row
{ key: "nickname", title: "昵称", type: "text", show: ["row"] }
// Do not display
{ key: "nickname", title: "昵称", type: "text", show: ["none"] }
```
```
--------------------------------
### Drawer Component Slot Example
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-components/31-drawer-抽屉.md
An example demonstrating how to use the title and default slots of the vk-data-drawer component.
```APIDOC
## vk-data-drawer Component Slot Example
### Description
This snippet illustrates how to utilize the `title` and `default` slots to customize the content of the `vk-data-drawer` component.
### Method
N/A (Component Usage)
### Endpoint
N/A (Component Usage)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```html
这是标题的插槽
这里是主内容插槽
```
### Response
N/A (Component Usage)
```
--------------------------------
### Icon Filtering Examples
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-components/25-icon-图标选择.md
Examples demonstrating how to use the 'filter' property for icon selection.
```APIDOC
## Icon Filtering
### Description
Examples of how to configure the `filter` property for the icon component.
### String Filter Mode
Filters icons based on a string prefix.
```js
{
key: "icon",
title: "图标",
type: "icon",
filter: "vk-"
}
```
### Function Filter Mode
Filters icons using a custom JavaScript function.
```js
{
key: "icon",
title: "图标",
type: "icon",
filter: (name) => {
return name.indexOf("vk-custom-icon") === 0 ? true : false;
}
}
```
```
--------------------------------
### Profit Sharing Configuration
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/vk-pay-advanced.md
Example of setting up profit sharing rules for a transaction.
```APIDOC
## Profit Sharing Configuration
### Description
Configures profit sharing for a transaction by defining rules for distributing funds.
### Method
POST
### Endpoint
/vkPay/createPayment
### Parameters
#### Request Body
- **context** (object) - Required - The execution context.
- **provider** (string) - Required - The payment provider (e.g., 'wxpay').
- **data** (object) - Required - Payment details:
- **total_fee** (number) - Required - Total transaction amount.
- **profit_sharing_rules** (array) - Required - Rules for profit sharing:
- **receiver_id** (string) - Required - Identifier for the profit recipient.
- **percentage** (number) - Required - Percentage of the total fee to be allocated.
- **description** (string) - Optional - Description of the rule.
- **profit_sharing** (boolean) - Required - Set to `true` to enable profit sharing.
- **profit_sharing_receivers** (array) - Required - List of receivers and their amounts.
- **receiver** (string) - Required - Receiver identifier.
- **amount** (number) - Required - Amount to be allocated.
- **description** (string) - Optional - Description of the allocation.
### Request Example
```javascript
async function setupProfitSharing(orderData) {
const { total_fee, profit_sharing_rules } = orderData;
const sharingAmounts = profit_sharing_rules.map(rule => {
return {
receiver: rule.receiver_id,
amount: Math.floor(total_fee * rule.percentage),
description: rule.description
};
});
const res = await vkPay.createPayment({
context,
provider: "wxpay",
data: {
...orderData,
profit_sharing: true,
profit_sharing_receivers: sharingAmounts
}
});
return res;
}
```
```
--------------------------------
### Vue: Drawer Component Example
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-element-examples.md
Provides an example of a drawer component using Vue and Element UI. It includes a button to open the drawer and allows for customization of direction and closing behavior.
```vue
打开抽屉
我来啦!
```
--------------------------------
### Vk-Data-Dialog Fullscreen Mode (Vue)
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-dialog-examples.md
This example shows how to configure the Vk-Data-Dialog to display in fullscreen mode by setting the 'fullscreen' prop to true. It also includes examples of setting width and height for the dialog.
```vue
```
--------------------------------
### vk-data-dialog Properties
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-dialog-examples.md
Details of the properties available for the vk-data-dialog component.
```APIDOC
## vk-data-dialog Component Properties
### Description
This section lists and describes the available properties for the `vk-data-dialog` component, which controls its behavior and appearance.
### Method
N/A (Component properties)
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
N/A
### Response
#### Success Response (200)
**Properties:**
- **v-model** (Boolean) - Controls the visibility of the dialog. Default: `false`.
- **title** (String) - The title displayed in the dialog header. Default: `''`.
- **width** (String) - The width of the dialog. Default: `'500px'`.
- **height** (String) - The height of the dialog. Default: `'auto'`.
- **mode** (String) - The mode of the dialog (e.g., 'form', 'table', 'normal'). Default: `'normal'`.
- **show-close** (Boolean) - Whether to display the close button. Default: `true`.
- **close-on-click-modal** (Boolean) - Whether the dialog can be closed by clicking on the modal background. Default: `true`.
- **close-on-press-escape** (Boolean) - Whether the dialog can be closed by pressing the ESC key. Default: `true`.
#### Response Example
N/A
```
--------------------------------
### Usage Example: Basic Slider
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-components/16-slider-滑块.md
Demonstrates the basic usage of the Slider component with default settings.
```APIDOC
## Basic Slider Usage
### Description
Shows a simple example of how to use the `el-slider` component.
### Method
N/A (Template Usage)
### Endpoint
N/A (Template Usage)
### Request Example
```html
```
```
--------------------------------
### Advanced Usage References
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-table-component.md
Provides links to advanced usage examples and complete demonstrations for the table component.
```APIDOC
## Advanced Usage References
### Description
Provides links to advanced usage examples and complete demonstrations for the table component.
### Links
- `/pages_template/components/table/table-easy`
- `/pages_template/components/table/table-pro`
- `/pages_template/components/table/table-slot`
```
--------------------------------
### Basic Upload Example (Vue)
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-upload-examples.md
Demonstrates the basic usage of the vk-data-upload component for uploading images. It includes functionality to clear and set the uploaded image list and displays the current form data.
```vue
清空值设置值表单数据
{{ form1 }}
```
--------------------------------
### vk-data-dialog Events
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-dialog-examples.md
Lists the events emitted by the vk-data-dialog component.
```APIDOC
## vk-data-dialog Component Events
### Description
This section outlines the events that can be emitted by the `vk-data-dialog` component, allowing for interaction with the dialog's lifecycle.
### Method
N/A (Component events)
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
N/A
### Response
#### Success Response (200)
**Events:**
- **confirm**: Triggered when the confirm button is clicked. No parameters.
- **cancel**: Triggered when the cancel button is clicked. No parameters.
- **close**: Triggered when the dialog is closed. No parameters.
- **open**: Triggered when the dialog is opened. No parameters.
#### Response Example
N/A
```
--------------------------------
### VK-UniCloud 云函数目录权限规范
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/cloud-framework-overview.md
展示了 VK-UniCloud 框架中云函数目录的权限划分标准。`sys` 目录下的函数需要特定权限验证,`kh` 目录下的函数需要登录验证,而 `pub` 目录下的函数则允许公开访问。这有助于实现不同级别的访问控制。
```bash
service/
├── admin/ # 管理端业务逻辑
│ └── [模块]/
│ ├── sys/ # 需要特定权限验证
│ ├── kh/ # 需要登录 + allow_login_background
│ └── pub/ # 公开访问
├── client/ # 客户端业务逻辑
│ └── [模块]/
│ ├── kh/ # 需要登录
│ └── pub/ # 公开访问
└── user/ # 用户中心服务
├── sys/ # 管理员权限
├── kh/ # 用户登录权限
└── pub/ # 公开访问
```
--------------------------------
### Icon Filtering in Universal Form (Function Mode)
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-components/25-icon-图标选择.md
Filters icons in a universal form using a custom function, allowing for more complex matching logic. This example only displays icons starting with 'vk-custom-icon'.
```javascript
{
key: "icon", title: "图标", type: "icon",
filter: (name) => {
return name.indexOf("vk-custom-icon") === 0 ? true : false;
},
}
```
--------------------------------
### Advanced Usage Examples
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/frontend-file-upload.md
Demonstrates advanced configurations for vk.uploadFile, including saving to asset library, custom paths, progress tracking, and multi-file uploads.
```APIDOC
## Advanced File Upload Scenarios
### Uploading and Saving to Asset Library
Uploads a file and saves its information to the admin asset library.
```javascript
// Select an image file
uni.chooseImage({
count: 1,
success: (res) => {
vk.uploadFile({
title: "Uploading and saving...",
file: res.tempFiles[0],
needSave: true, // Enable saving to asset library
category_id: "your_category_id", // Specify category ID
success: (uploadRes) => {
console.log('File uploaded and saved:', uploadRes);
}
});
}
});
```
### Customizing Cloud File Path
Specifies the destination path or directory for the uploaded file in the cloud.
```javascript
// Upload with a specific cloud path
vk.uploadFile({
title: "Uploading with custom path...",
file: fileObject, // Assume fileObject is obtained from user selection
cloudPath: "custom/directory/filename.jpg", // Full path
success: (uploadRes) => {
console.log('File saved to:', uploadRes.cloudPath);
}
});
// Upload to a specific cloud directory
vk.uploadFile({
title: "Uploading to custom directory...",
file: fileObject,
cloudDirectory: "user/avatars", // Directory only
success: (uploadRes) => {
console.log('File saved to:', uploadRes.cloudPath);
}
});
```
### Monitoring Upload Progress
Provides feedback on the upload status using the `onUploadProgress` callback.
```javascript
vk.uploadFile({
title: "Uploading with progress...",
file: fileObject,
onUploadProgress: (progressRes) => {
let { progress } = progressRes;
console.log(`Upload progress: ${progress}%`);
// Update UI with progress percentage
},
success: (uploadRes) => {
console.log('Upload complete:', uploadRes);
}
});
```
### Sequential Multi-File Upload
Uploads multiple files one after another.
```javascript
// Assume 'files' is an array of file objects obtained from user selection
async function uploadFilesSequentially(files) {
const results = [];
for (let i = 0; i < files.length; i++) {
try {
const result = await vk.uploadFile({
title: `Uploading file ${i + 1}...`,
file: files[i],
cloudDirectory: "gallery"
});
results.push(result);
} catch (error) {
console.error(`File ${i + 1} upload failed:`, error);
}
}
console.log('All files uploaded sequentially:', results);
// Process results
}
```
### Concurrent Multi-File Upload
Uploads multiple files simultaneously using `Promise.all`.
```javascript
// Assume 'files' is an array of file objects obtained from user selection
function uploadFilesConcurrently(files) {
const uploadPromises = files.map((file, index) => {
return vk.uploadFile({
title: `Uploading file ${index + 1}...`,
file: file,
cloudDirectory: "gallery"
});
});
Promise.all(uploadPromises)
.then(results => {
console.log('All files uploaded concurrently:', results);
// Process results
})
.catch(err => {
console.error('Some files failed to upload concurrently:', err);
});
}
```
```
--------------------------------
### Format, Get, and Offset Time with vk.pubfn
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/cloud-javascript-api.md
Demonstrates how to format dates, retrieve time ranges (today, month), and calculate time offsets using vk.pubfn.timeFormat, vk.pubfn.getCommonTime, vk.pubfn.getOffsetTime, and vk.pubfn.getDayOffsetStartAndEnd.
```javascript
// 云函数中的时间处理
module.exports = {
main: async (event, context) => {
// 格式化时间
const timeStr = vk.pubfn.timeFormat(new Date()) // 2024-01-01 10:10:10
const customTime = vk.pubfn.timeFormat(new Date(), "yyyy年MM月dd日")
// 获取时间范围
const { todayStart, todayEnd } = vk.pubfn.getCommonTime(new Date())
const { monthStart, monthEnd } = vk.pubfn.getCommonTime(new Date())
// 获取偏移时间
const timestamp = vk.pubfn.getOffsetTime(new Date(), {
hour: 1,
minutes: 30,
mode: "after"
})
// 获取相对时间的起止日期
const { startTime, endTime } = vk极速开发.getDayOffsetStartAndEnd(0) // 今日
const weekTime = vk.pubfn.getWeekOffsetStartAndEnd(-1) // 上周
const monthTime = vk.pubfn.getMonthOffsetStartAndEnd(1) // 下月
return {
code: 0,
data: {
timeStr,
todayRange: { todayStart, todayEnd },
weekTime,
monthTime
}
}
}
}
```
--------------------------------
### Transaction Management for Data Consistency
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/cloud-function-db-api.md
This example demonstrates how to ensure data consistency using database transactions. It shows the process of starting a transaction, performing multiple database operations (add order, update inventory), committing the transaction upon success, or rolling back in case of any errors.
```javascript
// 使用事务保证数据一致性
const transaction = await db.startTransaction();
try {
// 执行多个数据库操作
await transaction.collection('order').add(orderData);
await transaction.collection('inventory').update(inventoryData);
await transaction.commit();
res.code = 0;
res.msg = '操作成功';
} catch (error) {
await transaction.rollback();
res.code = -1;
res.msg = '操作失败: ' + error.message;
}
```
--------------------------------
### 列表渲染前后端一体模板 - 前端实现
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/list-rendering-template.md
提供了前端列表组件加载数据的示例代码,演示了如何调用云函数获取数据并更新UI。
```APIDOC
## 列表渲染前后端一体模板 - 前端实现
### 基础列表组件
```javascript
export default {
data() {
return {
list: [],
loading: false,
finished: false,
page: 1,
size: 10,
total: 0
}
},
methods: {
async loadData() {
if (this.loading) return
this.loading = true
try {
const res = await uniCloud.callFunction({
name: 'your-function-name',
data: {
page: this.page,
size: this.size,
// 其他查询参数
}
})
if (res.result.code === 0) {
const data = res.result.data
this.list = this.page === 1 ? data.list : [...this.list, ...data.list]
this.total = data.total
this.finished = !data.hasMore
this.page++
}
} catch (error) {
console.error('加载数据失败:', error)
} finally {
this.loading = false
}
}
}
}
```
```
--------------------------------
### Perform Array Operations with vk.pubfn
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/cloud-javascript-api.md
Provides examples for merging arrays, retrieving list items and their indices, converting arrays to JSON, extracting fields, and splitting arrays using vk.pubfn.arr_concat, vk.pubfn.getListItem, vk.pubfn.getListIndex, vk.pubfn.getListItemIndex, vk.pubfn.arrayToJson, vk.pubfn.arrayObjectGetArray, and vk.pubfn.splitArray.
```javascript
// 云函数中的数组操作
module.exports = {
main: async (event, context) => {
const { list1, list2 } = event
// 两个对象数组合并,去除重复数据
const mergedArray = vk.pubfn.arr_concat(list1, list2, "_id")
// 从对象数组中获取某一个对象
const item = vk.pubfn.getListItem(list, "_id", "001")
// 获取对象数组中某个元素的index
const index = vk.pubfn.getListIndex(list, "_id", "001")
// 同时获取对象和index
const { item: foundItem, index: foundIndex } = vk.pubfn.getListItemIndex(list, "_id", "001")
// 对象数组转JSON
const jsonObj = vk.pubfn.arrayToJson(list, "_id")
// 从数组中提取指定字段形成新数组
const idArray = vk.pubfn.arrayObjectGetArray(list, "_id")
// 分割数组
const chunks = vk.pubfn.splitArray([1,2,3,4,5,6,7,8,9,10], 3)
// 返回: [[1,2,3], [4,5,6], [7,8,9], [10]]
return {
code: 0,
data: {
mergedArray,
foundItem,
foundIndex,
jsonObj,
idArray,
chunks
}
}
}
}
```
--------------------------------
### Setup Profit Sharing
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/vk-pay-advanced.md
Provides a JavaScript function `setupProfitSharing` to configure and create a payment that includes profit sharing rules. It calculates sharing amounts based on a total fee and a list of rules, then uses `vkPay.createPayment` with `profit_sharing: true` and `profit_sharing_receivers`.
```javascript
// 分账配置示例
async function setupProfitSharing(orderData) {
const { total_fee, profit_sharing_rules } = orderData;
// 计算分账金额
const sharingAmounts = profit_sharing_rules.map(rule => {
return {
receiver: rule.receiver_id,
amount: Math.floor(total_fee * rule.percentage),
description: rule.description
};
});
// 创建分账订单
const res = await vkPay.createPayment({
context,
provider: "wxpay",
data: {
...orderData,
profit_sharing: true,
profit_sharing_receivers: sharingAmounts
}
});
return res;
}
```
--------------------------------
### Monthly User Registration Statistics for the Current Year
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/cloud-database-docs/4-database-aggregation.md
Calculates the number of users registered each month for the current year. It uses `vk.pubfn.getCommonTime()` to get the year's start and end dates for filtering and `$.dateToString` to format the registration date for monthly grouping. The results are sorted in descending order by month.
```javascript
let { yearStart, yearEnd } = vk.pubfn.getCommonTime();
res = await vk.baseDao.selects({
dbName: "uni-id-users",
pageIndex: 1,
pageSize: 1000,
whereJson: {
register_date : _.gte(yearStart).lte(yearEnd), // 只查询本年,不加此条件则查全表
},
groupJson: {
// _id是分组id, 将$register_date转为date,然后将date转为需要分组的date格式,直接分组
_id: $.dateToString({
date: $.add([new Date(0), "$register_date"]),
format: "%Y-%m",
timezone: "+08:00", // +08:00 代表北京时间(东八区)
onNull: null, // 可选。当 <日期表达式> 返回空或者不存在的时候,会返回此表达式指明的值。
}),
count: $.sum(1),
},
sortArr: [{ "name": "_id", "type": "desc" }]
});
```
--------------------------------
### VksPay Payment Call
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/vk-pay-advanced.md
Demonstrates how to initiate a payment using the VksPay provider, including specifying return URLs for synchronous callbacks.
```APIDOC
## VksPay Payment Call
### Description
This code example shows how to create a payment using the `vkPay.createPayment` function with the `vkspay` provider. It includes essential transaction details and a `return_url` for synchronous callback handling.
### Method
POST (Implied by `createPayment` call)
### Endpoint
N/A (Function Call)
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
```javascript
const vkPay = require("vk-uni-pay");
let res = await vkPay.createPayment({
context,
provider: "vkspay",
data: {
out_trade_no: "ORDER_" + Date.now(),
total_fee: 100,
subject: "商品名称",
type: "goods",
return_url: "https://example.com/return", // Synchronous callback URL
custom: {
user_id: "user_001",
goods_id: "goods_001"
}
}
});
```
### Request Example
```javascript
// Example of the data object passed to createPayment
{
"out_trade_no": "ORDER_1678886400000",
"total_fee": 100,
"subject": "商品名称",
"type": "goods",
"return_url": "https://example.com/return",
"custom": {
"user_id": "user_001",
"goods_id": "goods_001"
}
}
```
### Response
(Response structure depends on the payment provider's success/failure codes)
```json
{
"code": 0, // Example success code
"message": "Payment initiated successfully",
"payment_data": { ... } // Payment specific details
}
```
```
--------------------------------
### Success Response Examples
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/cloud-response-format.md
Illustrates different scenarios for successful responses, including basic success, success with data, and list data.
```APIDOC
## Success Responses
When `code` is 0, it signifies a successful operation. The frontend `vk.callFunction` will trigger the `success` callback.
### Basic Success Response
```javascript
{
code: 0,
msg: "Operation successful"
}
```
### Success Response with Data
```javascript
{
code: 0,
msg: "Fetch successful",
data: {
userInfo: {
_id: "user001",
nickname: "Zhang San",
avatar: "https://example.com/avatar.jpg"
}
}
}
```
### List Data Response
```javascript
{
code: 0,
msg: "Fetch successful",
data: {
rows: [
{ _id: "1", title: "Title 1" },
{ _id: "2", title: "Title 2" }
],
total: 100,
pageIndex: 1,
pageSize: 10,
hasMore: true
}
}
```
```
--------------------------------
### Implement File Preview Logic (JavaScript)
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-upload-examples.md
This JavaScript method, `handlePreview`, handles file previews. If the file is an image, it sets `previewImage` and `previewVisible` to show an image preview. For non-image files, it opens the file URL in a new tab for download or viewing.
```javascript
methods: {
handlePreview(file) {
if (file.type.includes('image/')) {
// 图片预览
this.previewImage = file.url
this.previewVisible = true
} else {
// 文件下载
window.open(file.url, '_blank')
}
}
}
```
--------------------------------
### Table Dialog Example (Vue)
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-dialog-examples.md
Illustrates embedding a vk-data-table within a vk-data-dialog. This allows displaying tabular data in a modal window. The example defines sample table data and column configurations.
```vue
打开表格弹窗
```
--------------------------------
### Search Documentation with Context7
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/README.md
Command to use Context7 for searching documentation within the VK Unicloud project. Replace '你的搜索关键词' with the actual search term.
```bash
# 使用 Context7 检索文档
context7 search "你的搜索关键词"
```
--------------------------------
### vk-data-detail Custom Formatting Example
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-detail-examples.md
Demonstrates how to apply custom formatting to a field within the vk-data-detail component. This example uses a `format` function with the `dayjs` library to display a timestamp in a user-friendly format.
```vue
```
--------------------------------
### VK-UniCloud API Usage and Aliases
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/frontend-javascript-api.md
Demonstrates how to use the vk.pubfn API in JavaScript and template files. Explains the shorthand '$fn' and specific prefixes like 'uni.vk' for NVUE and certain mini-programs (Alipay, Baidu, Douyin).
```javascript
// Standard usage in JS
console.log(vk.pubfn.hidden("15200000001", 3, 4));
// Shorthand usage in templates
console.log($fn.hidden("15200000001", 3, 4));
// NVUE page specific usage
export default {
data() {
return {
vk: uni.vk
};
}
}
// Alipay, Baidu, Douyin mini-program specific usage
var vk = uni.vk;
export default {
// ... other code
}
```
--------------------------------
### Fuzzy Query (Starts With)
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/cloud-database-docs/3-database-query-operators.md
Performs a fuzzy search to find records where a field starts with a specified string.
```APIDOC
## Fuzzy Query (Starts With)
### Description
This section explains how to perform a fuzzy search to find records where a specific field begins with a given substring.
### Method
`vk.baseDao.select`
### Query Parameters
* **`whereJson`** (Object) - Required - Filter criteria.
* Uses a `RegExp` object to match the beginning of the string.
### Request Example
```js
// Assuming 'searchvalue' holds the string to search for
let selectRes = await vk.baseDao.select({
dbName: "uni-id-users",
pageIndex: 1,
pageSize: 20,
whereJson: {
nickname: new RegExp('^' + searchvalue) // Matches 'nickname' starting with 'searchvalue'
}
});
```
### Response
* **`selectRes`**: An object containing the query results matching the fuzzy search criteria.
```
--------------------------------
### Upload - Basic Usage
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-upload-examples.md
Demonstrates the basic functionality of the upload component, allowing users to upload files and manage the uploaded file list.
```APIDOC
## Upload - Basic Usage
### Description
This example shows the fundamental usage of the upload component. It allows users to upload files, set a limit for the number of uploads, and view the uploaded file list. The component also supports clearing and setting the file list programmatically.
### Method
N/A (This is a component example, not an API endpoint)
### Endpoint
N/A
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None (Component usage)
### Request Example
```vue
清空值设置值表单数据
{{ form1 }}
```
### Response
#### Success Response (N/A)
#### Response Example
N/A
```
--------------------------------
### vk-data-detail Custom Rendering Example
Source: https://github.com/yunxiaozhi-ai/vk-unicloud-docs/blob/master/admin-detail-examples.md
Illustrates how to implement custom rendering for a field in the vk-data-detail component. This example uses a `render` function to inject custom HTML, styling a specific field's value with a red color.
```vue
${value}`
}
}
]"
>
```