### Complete Theme Switcher Component Example
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/theme-system.md
A full Vue component example for a theme switcher, allowing users to select themes, set preferences, and preview colors. It utilizes uView Plus's theme API for dynamic styling and application.
```javascript
主题选择偏好设置颜色预览{{ name }}
```
--------------------------------
### Frontend Development Workflow
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/DOCUMENTATION-SUMMARY.md
Outlines the typical steps for frontend development using uView-Plus, from requirement analysis to integrating code examples.
```markdown
需求分析 → 查看 README.md → 找到相关 API → 阅读 api-reference/*.md → 复制示例 → 集成到项目
```
--------------------------------
### Replace Resource with PUT
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/http-client.md
Completely replace a resource using the PUT method. This example demonstrates sending all fields for a post resource.
```javascript
const data = await uni.$u.http.put('/api/posts/456', {
title: 'New Title',
content: 'New Content',
author: 'John'
})
```
--------------------------------
### GET Request with Query Parameters
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/http-client.md
Perform a GET request and include query parameters in the URL for filtering or pagination. The `params` option in the config object is used for this.
```javascript
const data = await uni.$u.http.get('/api/users', {
params: {
page: 1,
limit: 10
}
})
```
--------------------------------
### Manage Themes
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/README.md
Get theme variables, set themes (e.g., 'dark', 'light'), and set theme preferences ('auto'). Also shows how to use theme variables in templates.
```javascript
// 获取当前主题
console.log(uni.$u.getThemeVars())
// 切换主题
uni.$u.setTheme('dark')
// 设置偏好
uni.$u.setThemePreference('auto')
// 在模板中使用
主题文本
```
--------------------------------
### Basic GET Request
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/http-client.md
Send a basic GET request to a specified URL. No additional configuration is needed for simple data retrieval.
```javascript
const response = await uni.$u.http.get('/api/users')
console.log(response.data)
```
--------------------------------
### Integrating API Calls with State Management (Vuex/Pinia)
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/http-client.md
Manage API data and loading states within your store using mutations and actions. This example demonstrates fetching users and updating the store.
```javascript
// store/user.js
export default {
state: {
users: [],
loading: false
},
mutations: {
setUsers(state, users) {
state.users = users
},
setLoading(state, loading) {
state.loading = loading
}
},
actions: {
async fetchUsers({ commit }) {
commit('setLoading', true)
try {
const users = await userService.getUsers()
commit('setUsers', users)
} catch (error) {
console.error('获取用户列表失败:', error)
} finally {
commit('setLoading', false)
}
}
}
}
```
--------------------------------
### Centralized API Calls with Services
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/http-client.md
Organize your API calls into service modules for better maintainability. This example shows a `userService` for managing user-related API endpoints.
```javascript
// services/user.js
export const userService = {
// 获取用户列表
getUsers(page = 1, limit = 10) {
return uni.$u.http.get('/api/users', {
params: { page, limit }
})
},
// 获取用户详情
getUserById(id) {
return uni.$u.http.get(`/api/users/${id}`)
},
// 创建用户
createUser(userData) {
return uni.$u.http.post('/api/users', userData)
},
// 更新用户
updateUser(id, userData) {
return uni.$u.http.patch(`/api/users/${id}`, userData)
},
// 删除用户
deleteUser(id) {
return uni.$u.http.delete(`/api/users/${id}`)
}
}
```
--------------------------------
### Get System Theme
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/configuration.md
Determine the current theme of the operating system ('light' or 'dark') using getSystemTheme(). This is useful for 'auto' theme preference.
```javascript
const systemTheme = uni.$u.getSystemTheme()
console.log(systemTheme) // 'light' 或 'dark'
```
--------------------------------
### http.get(url, config)
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/http-client.md
Sends a GET request to the specified URL. Supports query parameters and custom headers via the config object.
```APIDOC
## GET /api/users
### Description
Sends a GET request to the specified URL. Supports query parameters and custom headers via the config object.
### Method
GET
### Endpoint
/api/users
### Parameters
#### Query Parameters
- **params** (object) - Optional - Query parameters to be appended to the URL.
- **header** (object) - Optional - Custom headers to be sent with the request.
### Request Example
```javascript
// Basic GET request
const response = await uni.$u.http.get('/api/users')
console.log(response.data)
// With query parameters
const data = await uni.$u.http.get('/api/users', {
params: {
page: 1,
limit: 10
}
})
// With custom headers
const data = await uni.$u.http.get('/api/users', {
header: {
'Authorization': 'Bearer token123'
}
})
```
### Response
#### Success Response (200)
- **data** (any) - The data returned from the server.
```
--------------------------------
### GET Request with Custom Headers
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/http-client.md
Send a GET request with custom headers, such as for authentication. The `header` option in the config object allows specifying these headers.
```javascript
const data = await uni.$u.http.get('/api/users', {
header: {
'Authorization': 'Bearer token123'
}
})
```
--------------------------------
### Delete Resource with DELETE
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/http-client.md
Send a DELETE request to remove a resource. This example shows deleting a specific user by ID.
```javascript
const response = await uni.$u.http.delete('/api/users/123')
```
--------------------------------
### Get System Information with sys()
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/platform-utilities.md
Retrieve synchronous system information using the sys() function. This provides details like screen dimensions, window dimensions, status bar height, platform, OS version, device model, and system version string. Useful for layout calculations and adapting UI to device characteristics.
```javascript
const systemInfo = uni.$u.sys()
console.log(systemInfo.screenHeight) // 屏幕高度
console.log(systemInfo.statusBarHeight) // 状态栏高度
console.log(systemInfo.system) // "iOS 14.0" 或 "Android 11.0"
// 计算可用高度
const availableHeight = systemInfo.windowHeight - systemInfo.statusBarHeight
```
--------------------------------
### Debounce Function Example
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/animation-utilities.md
Use debounce to limit the rate at which a function can fire. This example shows how to apply it to an input event for search queries, ensuring the search function is only called after the user stops typing for a specified duration.
```javascript
function debounce(func: Function, wait = 500, immediate = false): void
```
```javascript
// 搜索输入框
```
--------------------------------
### Partial Update with PATCH
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/http-client.md
Use the PATCH method for partial updates to a resource. This example shows updating only the email address of a user, leaving other fields unchanged.
```javascript
const response = await uni.$u.http.patch('/api/users/123', {
email: 'newemail@example.com'
})
```
--------------------------------
### Make HTTP Requests
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/README.md
Perform GET and POST requests, and add interceptors for request headers. Supports asynchronous operations.
```javascript
// 发送 GET 请求
const data = await uni.$u.http.get('/api/users')
// 发送 POST 请求
const result = await uni.$u.http.post('/api/login', {
username: 'admin',
password: 'password123'
})
// 添加拦截器
uni.$u.http.interceptors.request.use((config) => {
config.header['Authorization'] = `Bearer ${token}`
return config
})
```
--------------------------------
### Configure Default Props for Multiple Components
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/configuration.md
Set global default values for various common components, including buttons, inputs, popups, and modals. This example demonstrates setting properties like type, size, placeholder, and more.
```javascript
uni.$u.setConfig({
props: {
button: {
type: 'primary',
size: 'normal',
disabled: false,
loading: false,
plain: false
},
input: {
clearable: true,
disabled: false,
placeholder: '请输入'
},
popup: {
closeOnClickOverlay: true,
closeOnClickModal: true
}
}
})
```
--------------------------------
### Get Theme Variables
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/configuration.md
Retrieve all color variables for the current theme using getThemeVars(). Use this to inspect available theme colors.
```javascript
const themeVars = uni.$u.getThemeVars()
console.log(themeVars['u-primary']) // #2979ff
```
--------------------------------
### Get User Theme Preference
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/configuration.md
Fetch the user's current theme preference, which can be 'auto', 'light', or 'dark'. This indicates how the theme is currently set.
```javascript
const preference = uni.$u.getThemePreference()
console.log(preference) // 'auto'、'light' 或 'dark'
```
--------------------------------
### Global HTTP Interceptor Setup
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/README.md
Configure global request and response interceptors for your HTTP client. This is useful for adding authentication tokens or handling API errors consistently. The interceptors are set up in the app.vue onLoad method.
```javascript
// 在 app.vue onLoad 中
uni.$u.http.interceptors.request.use(config => {
const token = uni.getStorageSync('token')
if (token) {
config.header = config.header || {}
config.header['Authorization'] = `Bearer ${token}`
}
return config
})
uni.$u.http.interceptors.response.use(response => {
// 处理业务状态码
if (response.data.code !== 0) {
uni.$u.toast(response.data.message)
return Promise.reject(response.data.message)
}
return response.data.data
})
```
--------------------------------
### Get Device Information with getDeviceInfo()
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/platform-utilities.md
Fetch device-specific information using getDeviceInfo(). This includes the device platform ('ios' or 'android'), model, brand, and device ID if available. Useful for device-specific features or analytics.
```javascript
const deviceInfo = uni.$u.getDeviceInfo()
console.log(deviceInfo.platform) // "ios" 或 "android"
console.log(deviceInfo.model) // "iPhone 12" 等
console.log(deviceInfo.brand) // "Apple"、"Samsung" 等
```
--------------------------------
### Add Authentication Token to Request
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/http-client.md
Example of adding an Authorization header with a Bearer token to the request config. Ensure a token is stored in uni.getStorageSync('token').
```javascript
// 添加认证令牌
uni.$u.http.interceptors.request.use(
(config) => {
const token = uni.getStorageSync('token')
if (token) {
config.header = config.header || {}
config.header['Authorization'] = `Bearer ${token}`
}
return config
}
)
```
--------------------------------
### Get Window Information with getWindowInfo()
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/platform-utilities.md
Obtain consistent window information across different platforms using getWindowInfo(). This function returns an object containing window width, window height, screen width, screen height, status bar height, and safe area details. Essential for responsive design and ensuring content fits within safe boundaries.
```javascript
const windowInfo = uni.$u.getWindowInfo()
console.log(windowInfo.windowWidth) // 可用窗口宽度
console.log(windowInfo.safeArea) // 安全区域对象
```
--------------------------------
### HTTP Client
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/DOCUMENTATION-SUMMARY.md
Details the HTTP client, including basic request methods (GET, POST, PUT, DELETE, PATCH), request configuration options, request and response interceptors, and error handling.
```APIDOC
## HTTP Client
### Description
Details the HTTP client, including basic request methods (GET, POST, PUT, DELETE, PATCH), request configuration options, request and response interceptors, and error handling.
### Methods
- **GET**: Retrieves data from a server.
- **POST**: Submits data to a server to create a resource.
- **PUT**: Updates a resource on the server.
- **DELETE**: Removes a resource from the server.
- **PATCH**: Partially updates a resource on the server.
### Features
- **Request Configuration Options**: Customizable settings for HTTP requests.
- **Request and Response Interceptors**: Allows modification of requests before they are sent and responses before they are processed.
- **Error Handling**: Mechanisms for managing and responding to HTTP errors.
```
--------------------------------
### Data List Loading and Pagination
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/README.md
Fetches user data in paginated batches using HTTP GET requests. Concatenates new data to the existing list and handles loading states. Displays toast messages on failure.
```javascript
export default {
data() {
return {
users: [],
page: 1,
limit: 10,
loading: false
}
},
async onLoad() {
await this.fetchUsers()
},
methods: {
async fetchUsers() {
this.loading = true
try {
const data = await uni.$u.http.get('/api/users', {
params: {
page: this.page,
limit: this.limit
}
})
if (this.page === 1) {
this.users = data.list
} else {
this.users = this.users.concat(data.list)
}
} catch (error) {
uni.$u.toast('加载失败')
} finally {
this.loading = false
}
},
loadMore() {
this.page++
this.fetchUsers()
}
}
}
```
--------------------------------
### Centralized API Management
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/README.md
Organize your API calls into a centralized object for better management and reusability. This example demonstrates how to define API services using $u.http.
```javascript
// services/api.js
export const userService = {
getUsers: () => uni.$u.http.get('/api/users'),
getUserById: (id) => uni.$u.http.get(`/api/users/${id}`),
createUser: (data) => uni.$u.http.post('/api/users', data),
updateUser: (id, data) => uni.$u.http.patch(`/api/users/${id}`, data),
deleteUser: (id) => uni.$u.http.delete(`/api/users/${id}`)
}
```
--------------------------------
### Form Validation with Utility Functions
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/README.md
Utilize the built-in testing utilities to simplify form input validation. This example shows how to create validator functions for common patterns like email, mobile, and ID cards.
```javascript
const validators = {
email: (value) => uni.$u.test.email(value),
mobile: (value) => uni.$u.test.mobile(value),
idCard: (value) => uni.$u.test.idCard(value),
amount: (value) => uni.$u.test.amount(value)
}
// 在表单中使用
if (!validators.email(form.email)) {
uni.$u.toast('邮箱格式不正确')
}
```
--------------------------------
### Initialize uView Plus
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/README.md
Mount the global $u object or configure settings during initialization. You can set units and theme colors.
```javascript
// main.ts
import { mount$u } from 'uview-plus'
mount$u() // 挂载全局 $u 对象
// 或在初始化时配置
uni.$u.setConfig({
config: {
unit: 'px',
color: {
'u-primary': '#007AFF'
}
}
})
```
--------------------------------
### Cross-Platform Application Initialization
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/platform-utilities.md
This snippet demonstrates how to initialize an application by fetching system and device information, performing platform-specific checks (iOS, Android, DevTools), and setting up initial configurations within the `onLaunch` lifecycle hook.
```javascript
// app.vue 或 main.ts
export default {
async onLaunch() {
// 1. 获取系统信息
const systemInfo = uni.$u.sys()
console.log('平台:', systemInfo.platform)
console.log('屏幕尺寸:', systemInfo.screenWidth, 'x', systemInfo.screenHeight)
// 2. 获取设备信息
const deviceInfo = uni.$u.getDeviceInfo()
console.log('设备品牌:', deviceInfo.brand)
// 3. 检查平台特定功能
if (uni.$u.os() === 'ios') {
// iOS 特定初始化
this.initializeIOS()
} else if (uni.$u.os() === 'android') {
// Android 特定初始化
this.initializeAndroid()
}
// 4. 判断是否为开发者工具
if (uni.$u.os() === 'devtools') {
console.log('在开发者工具中运行')
}
},
methods: {
initializeIOS() {
// iOS 特定代码
},
initializeAndroid() {
// Android 特定代码
},
navigateToUser(userId) {
// 导航到用户页面并传递参数
uni.$u.route.push({
url: '/pages/user/profile',
params: {
id: userId
}
})
},
goBack() {
const pages = uni.$u.pages()
if (pages.length > 1) {
uni.$u.route.back()
} else {
// 如果没有上一页,回到首页
uni.$u.route.relaunch({
url: '/pages/home/index'
})
}
}
}
}
```
--------------------------------
### Throttle Function Example
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/animation-utilities.md
Use throttle to ensure a function is called at most once within a given time period. This example demonstrates its use with a scroll event listener on a scroll-view component, limiting the execution of the handler function.
```javascript
function throttle(func: Function, wait = 500, immediate = true): void
```
```javascript
// 页面滚动监听
```
--------------------------------
### SystemInfo 类型定义
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/types.md
定义了系统信息的结构,包含 SDK 版本、设备品牌、操作系统信息等。通过 `uni.$u.sys()` 获取。
```typescript
interface SystemInfo {
SDKVersion: string // SDK 版本号
app: string // 应用名称(仅 APP)
brand: string // 设备品牌
browserVersion: string // 浏览器版本
deviceId: string // 设备 ID
deviceModel: string // 设备型号
deviceOrientation: string // 设备方向
errMsg: string // 错误信息
fontSizeSetting: number // 用户设置的字体大小
hasNotch: boolean // 是否有刘海
language: string // 系统语言
memorySize: number // 内存大小(仅 APP)
model: string // 设备型号
osName: string // 操作系统名称
osVersion: string // 操作系统版本
platform: string // 平台,如 'android'、'ios'、'windows'
safeArea: SafeArea // 安全区域
safeAreaInsets: SafeAreaInsets // 安全区域内边距
screenHeight: number // 屏幕高度(px)
screenWidth: number // 屏幕宽度(px)
statusBarHeight: number // 状态栏高度(px)
system: string // 系统名称和版本
top: number // 应用顶部距离(px)
uniCompileVersion: string // uni-app 编译版本
uniPlatform: string // uni-app 平台
uniRuntimeVersion: string // uni-app 运行时版本
version: string // 小程序基础库版本
windowHeight: number // 可用窗口高度(px)
windowTop: number // 窗口顶部距离(px)
windowWidth: number // 可用窗口宽度(px)
}
```
--------------------------------
### sys()
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/platform-utilities.md
Synchronously retrieves system information, including screen dimensions, status bar height, and device model. This is useful for layout calculations and device-specific adjustments.
```APIDOC
## sys()
### Description
Retrieves system information synchronously.
### Method
```javascript
function sys(): SystemInfo
```
### Returns
`SystemInfo` - An object containing system information.
Common properties:
- `screenWidth`: Screen width (px)
- `screenHeight`: Screen height (px)
- `windowWidth`: Window width (px)
- `windowHeight`: Window height (px)
- `statusBarHeight`: Status bar height (px)
- `platform`: Platform name
- `osVersion`: Operating system version
- `model`: Device model
- `system`: System version string
### Example
```javascript
const systemInfo = uni.$u.sys()
console.log(systemInfo.screenHeight) // Screen height
console.log(systemInfo.statusBarHeight) // Status bar height
console.log(systemInfo.system) // "iOS 14.0" or "Android 11.0"
// Calculate available height
const availableHeight = systemInfo.windowHeight - systemInfo.statusBarHeight
```
```
--------------------------------
### Theme System
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/DOCUMENTATION-SUMMARY.md
Explains the theme system, covering theme state management, theme setting methods (setTheme, setThemePreference, etc.), theme variable retrieval, and style/UI assistance.
```APIDOC
## Theme System
### Description
Explains the theme system, covering theme state management, theme setting methods (setTheme, setThemePreference, etc.), theme variable retrieval, and style/UI assistance.
### Features
- **Theme State Management**: Manages the current theme state of the application.
- **Theme Setting Methods**: Functions to set and change themes (e.g., `setTheme`, `setThemePreference`).
- **Theme Variable Retrieval**: Accesses and retrieves theme-related variables.
- **Style and UI Assistance**: Provides utilities to aid in styling and UI development based on the current theme.
```
--------------------------------
### Initialize WebView QR Code and JSBridge
Source: https://github.com/ijry/uview-plus/blob/3.x/src/static/app-plus/up-canvas/local.html
Sets up the UniApp JSBridge listener and defines the setContent function to render QR codes with optional logo overlays.
```javascript
* { margin: 0; padding: 0; }
document.addEventListener("UniAppJSBridgeReady", function() { // document.body.onclick = function() { // return uni.postMessage({ // data: { // action: "onClick" // } // }) // } uni.postMessage({ data: { action: "onJSBridgeReady" } }) }); window.setContent = function(params) { QRCode.toCanvas(document.getElementById('qrcode'), params.val, { width: params.size, height: params.size, margin: 0, color: { dark: params.foreground, light: params.background }, errorCorrectionLevel: 'H' }, function (error) { if (error) console.error(error) const canvas = document.getElementById('qrcode'); const ctx = canvas.getContext('2d'); // 2. 加载并绘制 logo if(params.icon) { const logo = new Image(); logo.crossOrigin = "anonymous"; // 避免跨域问题(如适用) logo.onload = () => { const logoSize = params.iconSize; // logo 宽高(建议不超过二维码宽高的 20%~25%) const x = (canvas.width - logoSize) / 2; const y = (canvas.height - logoSize) / 2; ctx.drawImage(logo, x, y, logoSize, logoSize); }; logo.src = params.icon; } console.log('success!'); } ) // var qrcode = new QRCode("qrcode", { // text: params.val, // width: params.size, // height: params.size, // colorDark : params.foreground, // colorLight : params.background, // correctLevel : QRCode.CorrectLevel.H // }); uni.postMessage({ data: { action: "qrcodeOk", imgData: '' } }) }
```
--------------------------------
### Configure Custom Icons
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/configuration.md
Set up custom icon fonts by specifying the font family and URL, and map custom icon names to their corresponding character codes.
```javascript
uni.$u.setConfig({
config: {
customIcon: {
family: 'my-icon',
url: 'https://example.com/fonts/my-icon.ttf' // 字体文件 URL
},
customIcons: {
'icon-home': '\e001', // 自定义图标映射
'icon-user': '\e002'
}
}
})
```
--------------------------------
### JavaScript Contract Test for u-guide Component
Source: https://github.com/ijry/uview-plus/blob/3.x/docs/superpowers/plans/2026-05-28-up-guide.md
This script verifies the existence and content of u-guide component files, including Vue components, props, defaults, types, and configuration files. It uses Node.js assertions to check file existence and content matching. Run this script to establish the contract for the u-guide component.
```javascript
import assert from 'node:assert/strict'
import fs from 'node:fs'
function toAbs(relativePath) {
return new URL(`../${relativePath}`, import.meta.url)
}
function exists(relativePath) {
return fs.existsSync(toAbs(relativePath))
}
function read(relativePath) {
return fs.readFileSync(toAbs(relativePath), 'utf8')
}
function assertContains(content, matcher, message) {
assert.match(content, matcher, message)
}
try {
assert.ok(
exists('src/uni_modules/uview-plus/components/u-guide/u-guide.vue'),
'expected u-guide.vue to exist'
)
assert.ok(
exists('src/uni_modules/uview-plus/components/u-guide/props.js'),
'expected guide props.js to exist'
)
assert.ok(
exists('src/uni_modules/uview-plus/components/u-guide/guide.js'),
'expected guide defaults guide.js to exist'
)
const guideDefaults = read('src/uni_modules/uview-plus/components/u-guide/guide.js')
assertContains(guideDefaults, /guide\s*:\s*{/, 'expected guide defaults object')
assertContains(guideDefaults, /storageKey:\s*['"]up-guide-default['"]/, 'expected default storageKey')
assertContains(guideDefaults, /once:\s*true/, 'expected once default true')
const guideProps = read('src/uni_modules/uview-plus/components/u-guide/props.js')
assertContains(guideProps, /defProps\.guide\.list/, 'expected list default from defProps.guide')
assertContains(guideProps, /defProps\.guide\.once/, 'expected once default from defProps.guide')
const guideVue = read('src/uni_modules/uview-plus/components/u-guide/u-guide.vue')
assertContains(guideVue, /name:\s*['"]up-guide['"]/, 'expected component name up-guide')
assertContains(
guideVue,
/emits:\s*\[\s*['"]update:show['"]\s*,\s*['"]change['"]\s*,\s*['"]skip['"]\s*,\s*['"]finish['"]\s*,\s*['"]close['"]\s*\]/,
'expected emits update:show/change/skip/finish/close'
)
assertContains(guideVue, /open\(\)\s*{/, 'expected open() method')
assertContains(guideVue, /close\(\s*remember\s*=\s*true\s*\)\s*{/, 'expected close(remember = true) method')
assertContains(guideVue, /reset\(\)\s*{/, 'expected reset() method')
const propsAggregator = read('src/uni_modules/uview-plus/libs/config/props.js')
assertContains(propsAggregator, /import Guide from ['"]\.\.\/\.\.\/components\/u-guide\/guide['"]/, 'expected props aggregator to import Guide defaults')
assertContains(propsAggregator, /\.\.\.Guide,/, 'expected props aggregator to merge Guide defaults')
assert.ok(
exists('src/uni_modules/uview-plus/types/comps/guide.d.ts'),
'expected types/comps/guide.d.ts to exist'
)
const guideTypes = read('src/uni_modules/uview-plus/types/comps/guide.d.ts')
assertContains(guideTypes, /export declare const Guide:/, 'expected Guide type export')
assertContains(guideTypes, /export declare const GuideRef:/, 'expected GuideRef type export')
const globalTypes = read('src/uni_modules/uview-plus/types/comps.d.ts')
assertContains(globalTypes, /\['up-guide'\]: typeof import\('\.\/comps\/guide'\)\['Guide'\]/, 'expected global component type up-guide')
const indexTypes = read('src/uni_modules/uview-plus/types/index.d.ts')
assertContains(indexTypes, /declare type UniGuideRef = typeof import\('\.\/comps\/guide'\)\['GuideRef'\]/, 'expected UniGuideRef alias')
assert.ok(
exists('src/pages/componentsC/guide/guide.vue'),
'expected demo page src/pages/componentsC/guide/guide.vue'
)
const pagesJson = read('src/pages.json')
assertContains(pagesJson, /"path"\s*:\s*"guide\/guide"/, 'expected pages.json route for guide demo')
const componentsConfig = read('src/pages/example/components.config.js')
assertContains(componentsConfig, /path:\s*['"]\/pages\/componentsC\/guide\/guide['"]/, 'expected components list entry for guide demo')
console.log('guide contract assertions passed')
} catch (error) {
console.error(error.message)
process.exit(1)
}
```
--------------------------------
### POST Request with Configuration
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/http-client.md
Execute a POST request with additional configuration options, such as a timeout. The `config` object allows for fine-tuning request behavior.
```javascript
const data = await uni.$u.http.post('/api/login', {
username: 'admin',
password: 'password123'
}, {
timeout: 10000
})
```
--------------------------------
### getWindowInfo()
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/platform-utilities.md
Fetches window information, providing consistent window size data across different platforms. This is essential for responsive UI design.
```APIDOC
## getWindowInfo()
### Description
Retrieves window information. Provides consistent window size data across different platforms.
### Method
```javascript
function getWindowInfo(): WindowInfo
```
### Returns
`WindowInfo` - An object containing window information.
Common properties:
- `windowWidth`: Window width
- `windowHeight`: Window height
- `screenWidth`: Screen width
- `screenHeight`: Screen height
- `statusBarHeight`: Status bar height
- `safeArea`: Safe area object
### Example
```javascript
const windowInfo = uni.$u.getWindowInfo()
console.log(windowInfo.windowWidth) // Usable window width
console.log(windowInfo.safeArea) // Safe area object
```
```
--------------------------------
### Get Nested Property Value
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/utility-functions.md
Access deeply nested object properties using getProperty with a dot-notation path. Returns an empty string if the property does not exist.
```javascript
const data = {user: {profile: {name: 'John'}}}
uni.$u.getProperty(data, 'user.profile.name') // "John"
uni.$u.getProperty(data, 'user.notExist') // ""
```
--------------------------------
### Handling Concurrent Requests with Promise.all
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/http-client.md
Efficiently fetch multiple resources simultaneously using `Promise.all`. This is useful when data from different endpoints is needed at the same time.
```javascript
// 并发获取多个资源
Promise.all([
uni.$u.http.get('/api/users'),
uni.$u.http.get('/api/posts'),
uni.$u.http.get('/api/comments')
]).then(([users, posts, comments]) => {
console.log('所有数据加载完成')
}).catch(error => {
console.error('某个请求失败:', error)
})
```
--------------------------------
### Detect Current Platform with os()
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/platform-utilities.md
Use the os() function to determine the current runtime environment. It returns a lowercase string representing the platform, such as 'ios', 'android', 'windows', 'macos', 'linux', or 'devtools'. Useful for conditional logic based on the execution environment.
```javascript
const platform = uni.$u.os()
if (platform === 'ios') {
// 仅在 iOS 上执行
console.log('在 iOS 设备上')
} else if (platform === 'android') {
// 仅在 Android 上执行
console.log('在 Android 设备上')
}
// 判断是否为移动平台
if (['ios', 'android'].includes(platform)) {
console.log('移动设备')
}
```
--------------------------------
### Animation Utilities
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/DOCUMENTATION-SUMMARY.md
Includes utilities for debouncing and throttling, floating-point arithmetic (add, sub, mul, div), and number precision handling, as well as color processing and gradients.
```APIDOC
## Animation Utilities
### Description
Includes utilities for debouncing and throttling, floating-point arithmetic (add, sub, mul, div), and number precision handling, as well as color processing and gradients.
### Functions
- **Debounce and Throttle**: Utilities for controlling function execution frequency.
- **Floating-Point Arithmetic**: Precise arithmetic operations for floating-point numbers.
- **Number Precision Handling**: Manages precision for numerical calculations.
- **Color Processing and Gradients**: Utilities for color manipulation and gradient generation.
```
--------------------------------
### SystemInfo
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/types.md
Represents system information obtained via `uni.$u.sys()`. It includes details about the device, operating system, screen dimensions, and SDK versions.
```APIDOC
## SystemInfo
### Description
System information object, obtained via `uni.$u.sys()`.
### Usage
```javascript
const sysInfo = uni.$u.sys()
console.log(sysInfo.screenWidth) // Screen width
console.log(sysInfo.platform) // Platform information
```
### Type Definition
```typescript
interface SystemInfo {
SDKVersion: string // SDK version number
app: string // Application name (APP only)
brand: string // Device brand
browserVersion: string // Browser version
deviceId: string // Device ID
deviceModel: string // Device model
deviceOrientation: string // Device orientation
errMsg: string // Error message
fontSizeSetting: number // User-set font size
hasNotch: boolean // Whether there is a notch
language: string // System language
memorySize: number // Memory size (APP only)
model: string // Device model
osName: string // Operating system name
osVersion: string // Operating system version
platform: string // Platform, e.g., 'android', 'ios', 'windows'
safeArea: SafeArea // Safe area
safeAreaInsets: SafeAreaInsets // Safe area insets
screenHeight: number // Screen height (px)
screenWidth: number // Screen width (px)
statusBarHeight: number // Status bar height (px)
system: string // System name and version
top: number // Application top distance (px)
uniCompileVersion: string // uni-app compile version
uniPlatform: string // uni-app platform
uniRuntimeVersion: string // uni-app runtime version
version: string // Mini program base library version
windowHeight: number // Usable window height (px)
windowTop: number // Window top distance (px)
windowWidth: number // Usable window width (px)
}
```
```
--------------------------------
### Set User Theme Preference
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/configuration.md
Configure the user's theme preference to 'auto' (system default), 'light' (forced light), or 'dark' (forced dark).
```javascript
// 根据系统设置
uni.$u.setThemePreference('auto')
// 强制浅色
uni.$u.setThemePreference('light')
// 强制深色
uni.$u.setThemePreference('dark')
```
--------------------------------
### Problem Troubleshooting Workflow
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/DOCUMENTATION-SUMMARY.md
Describes the process for troubleshooting issues in a uView-Plus project, involving checking documentation and comparing code.
```markdown
遇到问题 → 查看 types.md 或相关 API 文档 → 查看完整示例 → 对比自己代码 → 调整实现
```
--------------------------------
### Platform Utilities
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/DOCUMENTATION-SUMMARY.md
Provides utilities for platform detection (os()), system information retrieval, routing (push, back, replace, relaunch), and page stack management.
```APIDOC
## Platform Utilities
### Description
Provides utilities for platform detection (os()), system information retrieval, routing (push, back, replace, relaunch), and page stack management.
### Functions
- **Platform Detection**: Identifies the current operating system or platform.
- **System Information Retrieval**: Fetches details about the system environment.
- **Routing Utilities**: Functions for navigation within the application (push, back, replace, relaunch).
- **Page Stack Management**: Utilities for managing the history of pages.
```
--------------------------------
### Access Utility Functions
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/README.md
Utilize various utility functions for common tasks like time formatting, deep cloning, validation, debouncing, and color manipulation.
```javascript
// 时间格式化
uni.$u.timeFormat(Date.now(), 'yyyy-mm-dd hh:MM:ss')
// 深度克隆
const cloned = uni.$u.deepClone(originalObject)
// 验证
if (uni.$u.test.email(email)) {
console.log('邮箱格式正确')
}
// 防抖
uni.$u.debounce(searchFunction, 500)
// 颜色处理
const rgba = uni.$u.colorToRgba('#ff0000', 0.5)
```
--------------------------------
### os()
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/platform-utilities.md
Retrieves the current operating system platform. This function is useful for implementing platform-specific logic in your application.
```APIDOC
## os()
### Description
Retrieves the current operating system platform.
### Method
```javascript
function os(): string
```
### Returns
`string` - The name of the platform (lowercase).
Possible return values:
- `'android'` - Android device
- `'ios'` - iOS device
- `'windows'` - Windows platform
- `'macos'` - macOS platform
- `'linux'` - Linux platform
- `'devtools'` - Developer tools
### Example
```javascript
const platform = uni.$u.os()
if (platform === 'ios') {
// Execute only on iOS
console.log('On iOS device')
} else if (platform === 'android') {
// Execute only on Android
console.log('On Android device')
}
// Check if it's a mobile platform
if (['ios', 'android'].includes(platform)) {
console.log('Mobile device')
}
```
```
--------------------------------
### 获取系统信息示例
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/types.md
演示如何调用 `uni.$u.sys()` 获取系统信息对象,并访问其属性,如屏幕宽度和平台信息。
```javascript
const sysInfo = uni.$u.sys()
console.log(sysInfo.screenWidth) // 屏幕宽度
console.log(sysInfo.platform) // 平台信息
```
--------------------------------
### http.post(url, data, config)
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/http-client.md
Sends a POST request to the specified URL with the given data in the request body. Configuration options can be provided.
```APIDOC
## POST /api/users
### Description
Sends a POST request to the specified URL with the given data in the request body. Configuration options can be provided.
### Method
POST
### Endpoint
/api/users
### Parameters
#### Path Parameters
- **url** (string) - Required - The request URL.
#### Request Body
- **data** (any) - Optional - The data to send in the request body.
#### Query Parameters
- **config** (object) - Optional - Request configuration options, such as timeout or headers.
### Request Example
```javascript
// Basic POST request
const response = await uni.$u.http.post('/api/users', {
name: 'John',
email: 'john@example.com'
})
console.log(response.data)
// With configuration options
const data = await uni.$u.http.post('/api/login', {
username: 'admin',
password: 'password123'
}, {
timeout: 10000
})
// Form data submission
const data = await uni.$u.http.post('/api/upload', {
file: fileData
}, {
header: {
'Content-Type': 'multipart/form-data'
}
})
```
### Response
#### Success Response (200)
- **data** (any) - The data returned from the server.
```
--------------------------------
### Create SCSS Fixture for Legacy Theme Bridge
Source: https://github.com/ijry/uview-plus/blob/3.x/docs/superpowers/plans/2026-04-27-legacy-theme-bridge.md
This SCSS file defines legacy variables and imports uview-plus to test the bridge functionality. It includes a probe class to check for emitted CSS variables.
```scss
$u-primary: #123456;
$u-main-color: #112233;
$u-border-color: #445566;
@import "../../src/uni_modules/uview-plus/theme.scss";
@import "../../src/uni_modules/uview-plus/index.scss";
.legacy-bridge-probe {
color: var(--up-primary, #000000);
border-color: var(--up-border-color, #000000);
background-color: var(--up-bg-color, #ffffff);
}
```
--------------------------------
### Using Global Theme Variables in Vue Templates
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/theme-system.md
Demonstrates how to directly use global theme variables like 'u-primary' and 'u-light-color' within Vue templates for styling elements.
```javascript
// 在模板中使用
```
--------------------------------
### Show Loading Indicator Before Request
Source: https://github.com/ijry/uview-plus/blob/3.x/_autodocs/api-reference/http-client.md
Displays a '加载中...' loading indicator using uni.showLoading before the request is sent. Remember to hide it in the response interceptor.
```javascript
// 请求前显示加载指示
uni.$u.http.interceptors.request.use(
(config) => {
uni.showLoading({ title: '加载中...' })
return config
}
)
```