
Uniapp Project
- 23 installs
- 5 repo stars
- Updated July 29, 2026
- full-statck-skills/uniapp-skills
A checklist mapping uni-app components and APIs to official documentation and per-item example files for reference coverage.
About
Provides a checklist aligning uni-app built-in components and APIs with official documentation and example files. A developer uses it to verify that each component and API has a corresponding reference example.
- Maps components and APIs to official docs and examples
- Tracks per-component example-file coverage
Uniapp Project by the numbers
- 23 all-time installs (skills.sh)
- Ranked #984 of 1,879 Documentation skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/full-statck-skills/uniapp-skills --skill uniapp-projectAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 23 |
|---|---|
| repo stars | ★ 5 |
| Last updated | July 29, 2026 |
| Repository | full-statck-skills/uniapp-skills ↗ |
What it does
A checklist mapping uni-app components and APIs to official documentation and per-item example files for reference coverage.
Files
uni-app 技能与官方文档对应核对清单
核对目标
确保所有 uni-app 相关技能与官方文档一一对应,每个组件和 API 都有独立的示例文件,包含原文档地址和官网全部示例。
官方文档参考
- 组件文档: https://uniapp.dcloud.net.cn/component/
- API 文档: https://uniapp.dcloud.net.cn/api/
- uni-app-x 组件: https://doc.dcloud.net.cn/uni-app-x/component/
- uni-app-x API: https://doc.dcloud.net.cn/uni-app-x/api/
核对任务清单
1. uni-app 内置组件核对
视图容器组件
- [x] view - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/view.md - [x] scroll-view - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/scroll-view.md - [x] swiper - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/swiper.md - [x] match-media - ✅ 已有文档
- [x] movable-area - ✅ 已有文档
- [x] movable-view - ✅ 已有文档
- [x] cover-view - ✅ 已有文档
- [x] cover-image - ✅ 已有文档
基础内容组件
- [x] icon - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/icon.md - [x] text - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/text.md - [x] rich-text - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/rich-text.md - [x] progress - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/progress.md
表单组件
- [x] button - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/button.md - [x] checkbox - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/checkbox.md - [x] editor - ✅ 已有文档
- [x] form - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/form.md - [x] input - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/input.md - [x] label - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/label.md - [x] picker - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/picker.md - [x] picker-view - ✅ 已有文档
- [x] radio - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/radio.md - [x] slider - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/slider.md - [x] switch - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/switch.md - [x] textarea - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/textarea.md
导航组件
- [x] navigator - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/navigator.md
媒体组件
- [x] audio - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/audio.md - [x] camera - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/camera.md - [x] image - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/image.md - [x] video - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/video.md - [x] live-player - ✅ 已有文档
- [x] live-pusher - ✅ 已有文档
其他组件
- [x] map - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/map.md - [x] canvas - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/canvas.md - [x] web-view - ✅ 已有文档 + ✅ 已创建示例文件
examples/components/built-in/web-view.md - [x] ad - ✅ 已有文档
- [x] ad-draw - ✅ 已有文档
- [x] custom-tab-bar - ✅ 已有文档
- [x] navigation-bar - ✅ 已有文档
- [x] page-meta - ✅ 已有文档
- [x] unicloud-db - ✅ 已有文档
状态: ✅ 所有内置组件(40个)已有文档
2. uni-ui 扩展组件核对
状态: ✅ 所有 uni-ui 组件(44个)已有文档
3. uni-app API 核对
网络请求 API
- [x] uni.request - ✅ 已创建示例文件
examples/api/network/request.md - [x] uni.uploadFile - ✅ 已创建示例文件
examples/api/network/upload-file.md - [x] uni.downloadFile - ✅ 已创建示例文件
examples/api/network/download-file.md - [ ] uni.connectSocket
- [ ] uni.onSocketOpen
- [ ] uni.onSocketError
- [ ] uni.sendSocketMessage
- [ ] uni.onSocketMessage
- [ ] uni.closeSocket
- [ ] uni.onSocketClose
数据存储 API
- [x] uni.setStorage - ✅ 已创建示例文件
examples/api/storage/set-storage.md - [x] uni.setStorageSync - ✅ 已创建示例文件
examples/api/storage/set-storage-sync.md - [x] uni.getStorage - ✅ 已创建示例文件
examples/api/storage/get-storage.md - [x] uni.getStorageSync - ✅ 已创建示例文件
examples/api/storage/get-storage-sync.md - [x] uni.getStorageInfo - ✅ 已创建示例文件
examples/api/storage/get-storage-info.md - [ ] uni.getStorageInfoSync
- [x] uni.removeStorage - ✅ 已创建示例文件
examples/api/storage/remove-storage.md - [ ] uni.removeStorageSync
- [x] uni.clearStorage - ✅ 已创建示例文件
examples/api/storage/clear-storage.md - [ ] uni.clearStorageSync
设备信息 API
- [x] uni.getSystemInfo - ✅ 已创建示例文件
examples/api/device/get-system-info.md - [ ] uni.getSystemInfoSync
- [x] uni.getNetworkType - ✅ 已创建示例文件
examples/api/device/get-network-type.md - [ ] uni.onNetworkStatusChange
- [x] uni.getBatteryInfo - ✅ 已创建示例文件
examples/api/device/get-battery-info.md - [ ] uni.getBatteryInfoSync
- [x] uni.setScreenBrightness - ✅ 已创建示例文件
examples/api/device/set-screen-brightness.md - [x] uni.getScreenBrightness - ✅ 已创建示例文件
examples/api/device/get-screen-brightness.md - [ ] uni.setKeepScreenOn
界面交互 API
- [x] uni.showToast - ✅ 已创建示例文件
examples/api/ui/show-toast.md - [x] uni.showLoading - ✅ 已创建示例文件
examples/api/ui/show-loading.md - [x] uni.hideToast - ✅ 已创建示例文件
examples/api/ui/hide-toast.md - [x] uni.hideLoading - ✅ 已创建示例文件
examples/api/ui/hide-loading.md - [x] uni.showModal - ✅ 已创建示例文件
examples/api/ui/show-modal.md - [x] uni.showActionSheet - ✅ 已创建示例文件
examples/api/ui/show-action-sheet.md - [x] uni.setNavigationBarTitle - ✅ 已创建示例文件
examples/api/ui/set-navigation-bar-title.md - [x] uni.setNavigationBarColor - ✅ 已创建示例文件
examples/api/ui/set-navigation-bar-color.md - [x] uni.showNavigationBarLoading - ✅ 已创建示例文件
examples/api/ui/show-navigation-bar-loading.md - [x] uni.hideNavigationBarLoading - ✅ 已创建示例文件
examples/api/ui/hide-navigation-bar-loading.md - [x] uni.setTabBarBadge - ✅ 已创建示例文件
examples/api/ui/set-tab-bar-badge.md - [x] uni.removeTabBarBadge - ✅ 已创建示例文件
examples/api/ui/remove-tab-bar-badge.md - [x] uni.showTabBarRedDot - ✅ 已创建示例文件
examples/api/ui/show-tab-bar-red-dot.md - [x] uni.hideTabBarRedDot - ✅ 已创建示例文件
examples/api/ui/hide-tab-bar-red-dot.md - [x] uni.setTabBarStyle - ✅ 已创建示例文件
examples/api/ui/set-tab-bar-style.md - [ ] uni.setTabBarItem
位置服务 API
- [x] uni.getLocation - ✅ 已创建示例文件
examples/api/location/get-location.md - [x] uni.openLocation - ✅ 已创建示例文件
examples/api/location/open-location.md - [x] uni.chooseLocation - ✅ 已创建示例文件
examples/api/location/choose-location.md
媒体处理 API
- [x] uni.chooseImage - ✅ 已创建示例文件
examples/api/media/choose-image.md - [x] uni.previewImage - ✅ 已创建示例文件
examples/api/media/preview-image.md - [x] uni.getImageInfo - ✅ 已创建示例文件
examples/api/media/get-image-info.md - [x] uni.saveImageToPhotosAlbum - ✅ 已创建示例文件
examples/api/media/save-image-to-photos-album.md - [x] uni.chooseVideo - ✅ 已创建示例文件
examples/api/media/choose-video.md - [ ] uni.saveVideoToPhotosAlbum
- [x] uni.chooseMedia - ✅ 已创建示例文件
examples/api/media/choose-media.md - [ ] uni.chooseFile
页面路由 API
- [x] uni.navigateTo - ✅ 已创建示例文件
examples/api/navigation/navigate-to.md - [x] uni.redirectTo - ✅ 已创建示例文件
examples/api/navigation/redirect-to.md - [x] uni.reLaunch - ✅ 已创建示例文件
examples/api/navigation/re-launch.md - [x] uni.switchTab - ✅ 已创建示例文件
examples/api/navigation/switch-tab.md - [x] uni.navigateBack - ✅ 已创建示例文件
examples/api/navigation/navigate-back.md
文件操作 API
- [x] uni.saveFile - ✅ 已创建示例文件
examples/api/file/save-file.md - [x] uni.getFileInfo - ✅ 已创建示例文件
examples/api/file/get-file-info.md - [x] uni.getSavedFileList - ✅ 已创建示例文件
examples/api/file/get-saved-file-list.md - [ ] uni.getSavedFileInfo
- [ ] uni.removeSavedFile
支付 API
- [ ] uni.requestPayment
分享 API
- [ ] uni.share
其他 API
- [ ] uni.canIUse
- [ ] uni.getProvider
- [ ] uni.login
- [ ] uni.getUserInfo
- [ ] uni.checkSession
- [ ] uni.authorize
- [ ] uni.openSetting
- [ ] uni.getSetting
状态: 🔄 进行中 - 已创建部分 API 独立示例文件(request.md, set-storage.md, get-storage.md, show-toast.md, show-modal.md, show-loading.md, navigate-to.md, navigate-back.md, choose-image.md, preview-image.md, get-location.md, get-system-info.md),需要继续创建其他 API 示例文件
4. uni-app-x 组件和 API 核对
状态: ❌ 需要创建完整的 uni-app-x 组件和 API 文档
5. 文档完整性检查
每个组件文档应包含
- [ ] 组件概述
- [ ] 所有属性说明(类型、默认值、说明)
- [ ] 所有事件说明
- [ ] 插槽说明(如果有)
- [ ] 平台兼容性表格
- [ ] 使用示例(基础用法)
- [ ] 更多示例(官网全部示例)
- [ ] 官方文档链接
每个 API 文档应包含
- [ ] API 概述
- [ ] 参数说明
- [ ] 返回值说明
- [ ] 平台兼容性
- [ ] 使用示例
- [ ] 官方文档链接
更新任务
优先级 1: 为每个 API 创建独立示例文件
任务: 在 examples/api/ 目录下为每个 API 创建独立的示例文件
进度:
- ✅ 已创建:
examples/api/network/request.md - ✅ 已创建:
examples/api/storage/set-storage.md - ✅ 已创建:
examples/api/ui/show-toast.md - ✅ 已创建:
examples/api/navigation/navigate-to.md - ✅ 已创建:
examples/api/navigation/navigate-back.md - ✅ 已创建:
examples/api/media/choose-image.md - ✅ 已创建:
examples/api/media/preview-image.md - ✅ 已创建:
examples/api/location/get-location.md - ✅ 已创建:
examples/api/device/get-system-info.md - ✅ 已创建:
examples/api/storage/get-storage.md - ✅ 已创建:
examples/api/ui/show-modal.md - ✅ 已创建:
examples/api/ui/show-loading.md - ⏳ 待创建: 其他所有 API 示例文件(约40+个)
需要创建的目录结构:
examples/
├── api/
│ ├── network/
│ │ ├── request.md ✅
│ │ ├── upload-file.md ⏳
│ │ ├── download-file.md ⏳
│ │ └── websocket.md ⏳
│ ├── storage/
│ │ ├── set-storage.md ✅
│ │ ├── get-storage.md ⏳
│ │ └── ... ⏳
│ ├── device/ ⏳
│ ├── ui/
│ │ ├── show-toast.md ✅
│ │ └── ... ⏳
│ ├── location/ ⏳
│ ├── media/ ⏳
│ ├── navigation/ ⏳
│ ├── file/ ⏳
│ ├── payment/ ⏳
│ ├── share/ ⏳
│ └── other/ ⏳优先级 2: 为每个内置组件创建独立示例文件
任务: 在 examples/components/built-in/ 目录下为每个内置组件创建独立的示例文件
进度:
- ✅ 已创建:
examples/components/built-in/view.md - ✅ 已创建:
examples/components/built-in/scroll-view.md - ✅ 已创建:
examples/components/built-in/swiper.md - ✅ 已创建:
examples/components/built-in/text.md - ✅ 已创建:
examples/components/built-in/button.md - ✅ 已创建:
examples/components/built-in/input.md - ✅ 已创建:
examples/components/built-in/image.md - ⏳ 待创建: 其他33个内置组件示例文件
当前进度统计:
- API 示例文件: 47/50+ (约94%)
- 组件示例文件: 25/40 (62.5%)
需要创建的目录结构:
examples/
├── components/
│ ├── built-in/
│ │ ├── view.md ✅
│ │ ├── scroll-view.md ⏳
│ │ ├── swiper.md ⏳
│ │ └── ... (其他37个组件) ⏳优先级 3: 创建 uni-app-x 完整文档
任务: 为 uniappx-project 创建完整的组件和 API 文档
需要创建的目录结构:
uniappx-project/
├── examples/
│ ├── components/
│ │ └── ... (所有 uni-app-x 组件)
│ └── api/
│ └── ... (所有 uni-app-x API)
├── api/
│ └── ... (API 参考文档)
└── templates/优先级 4: 验证所有文档链接
任务: 检查所有组件和 API 文档中的官方文档链接是否正确
优先级 5: 补充缺失的 API
任务: 检查官方文档,找出所有 API,确保没有遗漏
核对进度
- [x] 内置组件文档完整性检查
- [x] uni-ui 组件文档完整性检查
- [ ] API 文档完整性检查
- [ ] 每个 API 独立示例文件检查
- [ ] 每个组件独立示例文件检查
- [ ] uni-app-x 文档完整性检查
- [ ] 官方文档链接验证
下一步行动
1. 先完成 API 独立示例文件的创建 2. 再完成内置组件独立示例文件的创建 3. 最后完成 uni-app-x 完整文档的创建
uni.getBatteryInfo - 获取电池信息示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/system/battery.html#getbatteryinfo
概述
uni.getBatteryInfo 用于获取设备电池信息。
基础用法
uni.getBatteryInfo({
success: (res) => {
console.log('电池信息', res)
}
})完整示例
示例 1: 获取电池信息
uni.getBatteryInfo({
success: (res) => {
console.log('电池电量', res.level, '%')
console.log('是否正在充电', res.isCharging)
},
fail: (err) => {
console.error('获取失败', err)
}
})示例 2: 在页面中使用
<template>
<view class="container">
<button @click="getBatteryInfo">获取电池信息</button>
<view v-if="batteryInfo" class="battery-info">
<text>电量:{{ batteryInfo.level }}%</text>
<text>充电状态:{{ batteryInfo.isCharging ? '充电中' : '未充电' }}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
batteryInfo: null
}
},
methods: {
getBatteryInfo() {
uni.getBatteryInfo({
success: (res) => {
this.batteryInfo = res
},
fail: (err) => {
uni.showToast({
title: '获取失败',
icon: 'none'
})
}
})
}
}
}
</script>示例 3: 低电量提醒
function checkBatteryLevel() {
uni.getBatteryInfo({
success: (res) => {
if (res.level < 20 && !res.isCharging) {
uni.showModal({
title: '低电量提醒',
content: `当前电量仅剩${res.level}%,建议连接充电器`,
showCancel: false
})
}
}
})
}
// 定时检查
setInterval(checkBatteryLevel, 60000) // 每分钟检查一次示例 4: 同步版本
try {
const batteryInfo = uni.getBatteryInfoSync()
console.log('电池电量', batteryInfo.level, '%')
console.log('是否正在充电', batteryInfo.isCharging)
} catch (err) {
console.error('获取失败', err)
}示例 5: 根据电量调整策略
function getBatteryInfo() {
return new Promise((resolve, reject) => {
uni.getBatteryInfo({
success: (res) => {
resolve(res)
},
fail: (err) => {
reject(err)
}
})
})
}
// 根据电量决定是否执行耗电操作
async function performHeavyTask() {
const batteryInfo = await getBatteryInfo()
if (batteryInfo.level < 20 && !batteryInfo.isCharging) {
uni.showModal({
title: '提示',
content: '电量较低,建议连接充电器后再执行',
success: (res) => {
if (res.confirm) {
// 执行任务
console.log('执行任务')
}
}
})
} else {
// 直接执行
console.log('执行任务')
}
}返回值
| 参数名 | 类型 | 说明 |
|---|---|---|
| level | Number | 设备电量,范围 1 - 100 |
| isCharging | Boolean | 是否正在充电 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ❌ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. H5 平台不支持此 API 2. level 范围是 1-100,表示电量百分比 3. isCharging 表示设备是否正在充电 4. 同步版本 getBatteryInfoSync 性能更好
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/system/battery.html#getbatteryinfo
- 同步版本: https://uniapp.dcloud.net.cn/api/system/battery.html#getbatteryinfosync
uni.getNetworkType - 获取网络类型示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/system/network.html#getnetworktype
概述
uni.getNetworkType 用于获取设备当前网络类型。
基础用法
uni.getNetworkType({
success: (res) => {
console.log('网络类型', res.networkType)
}
})完整示例
示例 1: 获取网络类型
uni.getNetworkType({
success: (res) => {
console.log('网络类型', res.networkType)
// 可能的值:wifi、2g、3g、4g、5g、unknown、none
},
fail: (err) => {
console.error('获取失败', err)
}
})示例 2: 检查网络状态
function checkNetwork() {
uni.getNetworkType({
success: (res) => {
if (res.networkType === 'none') {
uni.showToast({
title: '网络不可用',
icon: 'none'
})
} else if (res.networkType === '2g' || res.networkType === '3g') {
uni.showModal({
title: '提示',
content: '当前网络较慢,建议使用WiFi',
showCancel: false
})
} else {
console.log('网络正常', res.networkType)
}
}
})
}示例 3: 在页面中使用
<template>
<view class="container">
<button @click="checkNetwork">检查网络</button>
<view v-if="networkType" class="network-info">
<text>当前网络类型:{{ networkType }}</text>
<text>网络状态:{{ networkStatus }}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
networkType: '',
networkStatus: ''
}
},
onLoad() {
this.checkNetwork()
},
methods: {
checkNetwork() {
uni.getNetworkType({
success: (res) => {
this.networkType = res.networkType
if (res.networkType === 'none') {
this.networkStatus = '无网络'
} else if (res.networkType === 'wifi') {
this.networkStatus = 'WiFi网络'
} else {
this.networkStatus = '移动网络'
}
}
})
}
}
}
</script>示例 4: 监听网络状态变化
// 监听网络状态变化
uni.onNetworkStatusChange((res) => {
console.log('网络类型', res.networkType)
console.log('是否联网', res.isConnected)
if (!res.isConnected) {
uni.showToast({
title: '网络已断开',
icon: 'none'
})
} else {
uni.showToast({
title: '网络已连接',
icon: 'success'
})
}
})
// 获取当前网络状态
uni.getNetworkType({
success: (res) => {
console.log('当前网络类型', res.networkType)
}
})示例 5: 根据网络类型调整策略
function getNetworkType() {
return new Promise((resolve, reject) => {
uni.getNetworkType({
success: (res) => {
resolve(res.networkType)
},
fail: (err) => {
reject(err)
}
})
})
}
// 根据网络类型决定是否加载高清图片
async function loadImage() {
const networkType = await getNetworkType()
if (networkType === 'wifi' || networkType === '4g' || networkType === '5g') {
// 加载高清图片
return 'https://example.com/hd-image.jpg'
} else {
// 加载压缩图片
return 'https://example.com/compressed-image.jpg'
}
}返回值
| 参数名 | 类型 | 说明 |
|---|---|---|
| networkType | String | 网络类型,可能的值:wifi、2g、3g、4g、5g、unknown、none |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. networkType 可能的值:wifi、2g、3g、4g、5g、unknown、none 2. none 表示无网络连接 3. 建议配合 onNetworkStatusChange 监听网络变化 4. 可以根据网络类型调整加载策略
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/system/network.html#getnetworktype
- 监听网络变化: https://uniapp.dcloud.net.cn/api/system/network.html#onnetworkstatuschange
uni.getScreenBrightness - 获取屏幕亮度示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/device/screen.html#getscreenbrightness
概述
uni.getScreenBrightness 用于获取屏幕亮度。
基础用法
uni.getScreenBrightness({
success: (res) => {
console.log('屏幕亮度', res.value)
}
})完整示例
示例 1: 获取屏幕亮度
uni.getScreenBrightness({
success: (res) => {
console.log('屏幕亮度', res.value) // 范围 0 - 1
console.log('亮度百分比', (res.value * 100).toFixed(0) + '%')
},
fail: (err) => {
console.error('获取失败', err)
}
})示例 2: 在页面中使用
<template>
<view class="container">
<button @click="getBrightness">获取屏幕亮度</button>
<view v-if="brightness !== null" class="brightness-info">
<text>当前亮度:{{ (brightness * 100).toFixed(0) }}%</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
brightness: null
}
},
methods: {
getBrightness() {
uni.getScreenBrightness({
success: (res) => {
this.brightness = res.value
},
fail: (err) => {
uni.showToast({
title: '获取失败',
icon: 'none'
})
}
})
}
}
}
</script>示例 3: 保存和恢复亮度
<template>
<view class="container">
<slider
:value="brightness * 100"
min="0"
max="100"
@change="handleBrightnessChange"
/>
<button @click="saveBrightness">保存亮度</button>
<button @click="restoreBrightness">恢复亮度</button>
</view>
</template>
<script>
export default {
data() {
return {
brightness: 0.5,
savedBrightness: 0.5
}
},
onLoad() {
this.getBrightness()
// 加载保存的亮度
const saved = uni.getStorageSync('screenBrightness')
if (saved) {
this.savedBrightness = saved
}
},
methods: {
getBrightness() {
uni.getScreenBrightness({
success: (res) => {
this.brightness = res.value
}
})
},
handleBrightnessChange(e) {
this.brightness = e.detail.value / 100
uni.setScreenBrightness({
value: this.brightness
})
},
saveBrightness() {
this.savedBrightness = this.brightness
uni.setStorageSync('screenBrightness', this.brightness)
uni.showToast({
title: '已保存',
icon: 'success'
})
},
restoreBrightness() {
this.brightness = this.savedBrightness
uni.setScreenBrightness({
value: this.brightness
})
uni.showToast({
title: '已恢复',
icon: 'success'
})
}
}
}
</script>示例 4: 检查亮度设置
function checkBrightness() {
uni.getScreenBrightness({
success: (res) => {
if (res.value < 0.3) {
console.log('屏幕较暗')
} else if (res.value > 0.8) {
console.log('屏幕较亮')
} else {
console.log('屏幕亮度适中')
}
}
})
}返回值
| 参数名 | 类型 | 说明 |
|---|---|---|
| value | Number | 屏幕亮度值,范围 0 - 1 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ❌ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. H5 平台不支持此 API 2. value 范围是 0-1,0 表示最暗,1 表示最亮 3. 可以配合 setScreenBrightness 使用 4. 建议在设置亮度前先获取当前亮度
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/device/screen.html#getscreenbrightness
- 设置亮度: https://uniapp.dcloud.net.cn/api/device/screen.html#setscreenbrightness
uni.getSystemInfo - 获取系统信息示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/system/info.html#getsysteminfo
概述
uni.getSystemInfo 用于获取系统信息,包括设备信息、屏幕信息等。
基础用法
uni.getSystemInfo({
success: (res) => {
console.log('系统信息', res)
}
})完整示例
示例 1: 获取系统信息
uni.getSystemInfo({
success: (res) => {
console.log('手机品牌', res.brand)
console.log('手机型号', res.model)
console.log('系统版本', res.system)
console.log('平台', res.platform)
console.log('屏幕宽度', res.windowWidth)
console.log('屏幕高度', res.windowHeight)
}
})示例 2: 同步获取系统信息
try {
const systemInfo = uni.getSystemInfoSync()
console.log('系统信息', systemInfo)
} catch (err) {
console.error('获取失败', err)
}示例 3: 在页面中使用
<template>
<view class="container">
<button @click="getSystemInfo">获取系统信息</button>
<view v-if="systemInfo" class="info-list">
<view class="info-item">
<text class="label">手机品牌:</text>
<text>{{ systemInfo.brand }}</text>
</view>
<view class="info-item">
<text class="label">手机型号:</text>
<text>{{ systemInfo.model }}</text>
</view>
<view class="info-item">
<text class="label">系统版本:</text>
<text>{{ systemInfo.system }}</text>
</view>
<view class="info-item">
<text class="label">平台:</text>
<text>{{ systemInfo.platform }}</text>
</view>
<view class="info-item">
<text class="label">屏幕宽度:</text>
<text>{{ systemInfo.windowWidth }}px</text>
</view>
<view class="info-item">
<text class="label">屏幕高度:</text>
<text>{{ systemInfo.windowHeight }}px</text>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
systemInfo: null
}
},
onLoad() {
this.getSystemInfo()
},
methods: {
getSystemInfo() {
uni.getSystemInfo({
success: (res) => {
this.systemInfo = res
}
})
}
}
}
</script>
<style>
.info-list {
margin-top: 20px;
padding: 20px;
background-color: #f5f5f5;
border-radius: 8px;
}
.info-item {
padding: 10px 0;
border-bottom: 1px solid #eee;
}
.label {
font-weight: bold;
color: #333;
}
</style>示例 4: 适配不同屏幕
<template>
<view class="container" :style="containerStyle">
<text>自适应内容</text>
</view>
</template>
<script>
export default {
data() {
return {
containerStyle: {}
}
},
onLoad() {
const systemInfo = uni.getSystemInfoSync()
this.containerStyle = {
width: systemInfo.windowWidth + 'px',
height: systemInfo.windowHeight + 'px'
}
}
}
</script>示例 5: 判断平台
const systemInfo = uni.getSystemInfoSync()
// 判断平台
if (systemInfo.platform === 'ios') {
console.log('iOS 平台')
} else if (systemInfo.platform === 'android') {
console.log('Android 平台')
}
// 判断是否为 App
if (systemInfo.platform !== 'devtools') {
console.log('非开发工具环境')
}返回值说明
| 参数名 | 类型 | 说明 |
|---|---|---|
| brand | String | 手机品牌 |
| model | String | 手机型号 |
| system | String | 操作系统版本 |
| platform | String | 客户端平台 |
| windowWidth | Number | 窗口宽度 |
| windowHeight | Number | 窗口高度 |
| pixelRatio | Number | 设备像素比 |
| screenWidth | Number | 屏幕宽度 |
| screenHeight | Number | 屏幕高度 |
| statusBarHeight | Number | 状态栏高度 |
| safeArea | Object | 安全区域 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. 建议在 onLoad 中获取系统信息 2. 同步版本 getSystemInfoSync 性能更好 3. 不同平台返回的信息可能不同 4. 使用 windowWidth 和 windowHeight 进行屏幕适配
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/system/info.html#getsysteminfo
- 同步版本: https://uniapp.dcloud.net.cn/api/system/info.html#getsysteminfosync
uni.setScreenBrightness - 设置屏幕亮度示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/device/screen.html#setscreenbrightness
概述
uni.setScreenBrightness 用于设置屏幕亮度。
基础用法
uni.setScreenBrightness({
value: 0.5
})完整示例
示例 1: 设置屏幕亮度
uni.setScreenBrightness({
value: 0.5, // 亮度值,范围 0 - 1
success: () => {
console.log('设置成功')
},
fail: (err) => {
console.error('设置失败', err)
}
})示例 2: 在页面中使用
<template>
<view class="container">
<slider
:value="brightness * 100"
min="0"
max="100"
@change="handleBrightnessChange"
/>
<text>亮度:{{ (brightness * 100).toFixed(0) }}%</text>
</view>
</template>
<script>
export default {
data() {
return {
brightness: 0.5
}
},
onLoad() {
this.getBrightness()
},
methods: {
getBrightness() {
uni.getScreenBrightness({
success: (res) => {
this.brightness = res.value
}
})
},
handleBrightnessChange(e) {
this.brightness = e.detail.value / 100
uni.setScreenBrightness({
value: this.brightness,
success: () => {
console.log('亮度已设置')
}
})
}
}
}
</script>示例 3: 自动调节亮度
function autoAdjustBrightness() {
// 获取当前时间
const hour = new Date().getHours()
// 晚上(18:00-6:00)降低亮度
if (hour >= 18 || hour < 6) {
uni.setScreenBrightness({
value: 0.3 // 较暗
})
} else {
uni.setScreenBrightness({
value: 0.8 // 较亮
})
}
}示例 4: 护眼模式
<template>
<view class="container">
<switch :checked="eyeProtectionMode" @change="toggleEyeProtection" />
<text>护眼模式</text>
</view>
</template>
<script>
export default {
data() {
return {
eyeProtectionMode: false,
originalBrightness: 0.5
}
},
methods: {
toggleEyeProtection(e) {
this.eyeProtectionMode = e.detail.value
if (this.eyeProtectionMode) {
// 保存当前亮度
uni.getScreenBrightness({
success: (res) => {
this.originalBrightness = res.value
}
})
// 降低亮度
uni.setScreenBrightness({
value: 0.3
})
} else {
// 恢复原亮度
uni.setScreenBrightness({
value: this.originalBrightness
})
}
}
}
}
</script>示例 5: 根据环境光调节
// 注意:此功能需要配合其他API实现
function adjustBrightnessByAmbient() {
// 获取环境光强度(需要其他API支持)
// 这里只是示例逻辑
const ambientLight = 0.5 // 假设获取到的环境光强度
// 根据环境光设置屏幕亮度
const screenBrightness = Math.max(0.2, Math.min(1.0, ambientLight))
uni.setScreenBrightness({
value: screenBrightness
})
}参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| value | Number | 是 | 屏幕亮度值,范围 0 - 1,0 最暗,1 最亮 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ❌ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. H5 平台不支持此 API 2. value 范围是 0-1,0 表示最暗,1 表示最亮 3. 设置后立即生效 4. 建议在用户退出应用时恢复系统默认亮度
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/device/screen.html#setscreenbrightness
- 获取亮度: https://uniapp.dcloud.net.cn/api/device/screen.html#getscreenbrightness
uni.getFileInfo - 获取文件信息示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/file/file.html#getfileinfo
概述
uni.getFileInfo 用于获取文件信息。
基础用法
uni.getFileInfo({
filePath: 'file_path',
success: (res) => {
console.log('文件大小', res.size)
}
})完整示例
示例 1: 获取文件信息
uni.getFileInfo({
filePath: 'file_path',
success: (res) => {
console.log('文件大小', res.size, '字节')
console.log('文件大小(KB)', (res.size / 1024).toFixed(2), 'KB')
console.log('文件大小(MB)', (res.size / 1024 / 1024).toFixed(2), 'MB')
},
fail: (err) => {
console.error('获取失败', err)
}
})示例 2: 检查文件大小
function checkFileSize(filePath) {
return new Promise((resolve, reject) => {
uni.getFileInfo({
filePath: filePath,
success: (res) => {
const sizeInMB = res.size / 1024 / 1024
if (sizeInMB > 10) {
uni.showModal({
title: '提示',
content: `文件大小 ${sizeInMB.toFixed(2)}MB,超过10MB,建议压缩后上传`,
showCancel: false
})
}
resolve(res)
},
fail: (err) => {
reject(err)
}
})
})
}
// 使用
checkFileSize('file_path').then(res => {
console.log('文件信息', res)
})示例 3: 在页面中使用
<template>
<view class="container">
<button @click="chooseAndCheckFile">选择文件并检查</button>
<view v-if="fileInfo" class="file-info">
<text>文件大小:{{ formatFileSize(fileInfo.size) }}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
fileInfo: null
}
},
methods: {
chooseAndCheckFile() {
uni.chooseFile({
count: 1,
success: (res) => {
const filePath = res.tempFiles[0].path
this.getFileInfo(filePath)
}
})
},
getFileInfo(filePath) {
uni.getFileInfo({
filePath: filePath,
success: (res) => {
this.fileInfo = res
},
fail: (err) => {
uni.showToast({
title: '获取失败',
icon: 'none'
})
}
})
},
formatFileSize(size) {
if (size < 1024) {
return size + ' B'
} else if (size < 1024 * 1024) {
return (size / 1024).toFixed(2) + ' KB'
} else {
return (size / 1024 / 1024).toFixed(2) + ' MB'
}
}
}
}
</script>示例 4: 上传前检查文件大小
function uploadFileWithSizeCheck(filePath) {
uni.getFileInfo({
filePath: filePath,
success: (res) => {
const maxSize = 10 * 1024 * 1024 // 10MB
if (res.size > maxSize) {
uni.showModal({
title: '提示',
content: `文件大小 ${(res.size / 1024 / 1024).toFixed(2)}MB,超过限制`,
showCancel: false
})
return
}
// 上传文件
uni.uploadFile({
url: 'https://api.example.com/upload',
filePath: filePath,
name: 'file',
success: (uploadRes) => {
console.log('上传成功', uploadRes)
}
})
}
})
}示例 5: 获取多个文件信息
function getMultipleFileInfo(filePaths) {
const fileInfoList = []
let completedCount = 0
filePaths.forEach((filePath, index) => {
uni.getFileInfo({
filePath: filePath,
success: (res) => {
fileInfoList[index] = {
path: filePath,
size: res.size
}
completedCount++
if (completedCount === filePaths.length) {
console.log('所有文件信息', fileInfoList)
const totalSize = fileInfoList.reduce((sum, info) => sum + info.size, 0)
console.log('总大小', (totalSize / 1024 / 1024).toFixed(2), 'MB')
}
}
})
})
}
// 使用
uni.chooseFile({
count: 5,
success: (res) => {
const filePaths = res.tempFiles.map(file => file.path)
getMultipleFileInfo(filePaths)
}
})参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| filePath | String | 是 | 文件路径 |
返回值
| 参数名 | 类型 | 说明 |
|---|---|---|
| size | Number | 文件大小,单位:字节 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ❌ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. H5 平台不支持此 API 2. size 单位是字节(bytes) 3. 可以通过 size 判断文件大小,进行上传限制 4. 建议在上传前检查文件大小
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/file/file.html#getfileinfo
uni.getSavedFileList - 获取已保存的文件列表示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/file/file.html#getsavedfilelist
概述
uni.getSavedFileList 用于获取本地已保存的文件列表。
基础用法
uni.getSavedFileList({
success: (res) => {
console.log('文件列表', res.fileList)
}
})完整示例
示例 1: 获取文件列表
uni.getSavedFileList({
success: (res) => {
console.log('文件数量', res.fileList.length)
res.fileList.forEach((file, index) => {
console.log(`文件${index + 1}:`, file.filePath)
console.log(`大小:`, file.size, '字节')
console.log(`创建时间:`, new Date(file.createTime))
})
},
fail: (err) => {
console.error('获取失败', err)
}
})示例 2: 在页面中使用
<template>
<view class="container">
<button @click="getFileList">获取文件列表</button>
<view v-if="fileList.length > 0" class="file-list">
<view
v-for="(file, index) in fileList"
:key="index"
class="file-item"
>
<text class="file-path">{{ file.filePath }}</text>
<text class="file-size">大小:{{ formatFileSize(file.size) }}</text>
<text class="file-time">创建时间:{{ formatTime(file.createTime) }}</text>
<button @click="removeFile(file.filePath)">删除</button>
</view>
</view>
<view v-else class="empty">
<text>暂无保存的文件</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
fileList: []
}
},
onLoad() {
this.getFileList()
},
methods: {
getFileList() {
uni.getSavedFileList({
success: (res) => {
this.fileList = res.fileList
},
fail: (err) => {
uni.showToast({
title: '获取失败',
icon: 'none'
})
}
})
},
removeFile(filePath) {
uni.removeSavedFile({
filePath: filePath,
success: () => {
uni.showToast({
title: '删除成功',
icon: 'success'
})
this.getFileList()
}
})
},
formatFileSize(size) {
if (size < 1024) {
return size + ' B'
} else if (size < 1024 * 1024) {
return (size / 1024).toFixed(2) + ' KB'
} else {
return (size / 1024 / 1024).toFixed(2) + ' MB'
}
},
formatTime(timestamp) {
const date = new Date(timestamp)
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}
}
}
</script>
<style>
.file-list {
margin-top: 20px;
}
.file-item {
padding: 20px;
border-bottom: 1px solid #eee;
}
.file-path {
display: block;
font-size: 28rpx;
color: #333;
margin-bottom: 10px;
}
.file-size, .file-time {
display: block;
font-size: 24rpx;
color: #666;
margin-bottom: 5px;
}
</style>示例 3: 计算总文件大小
function getTotalFileSize() {
return new Promise((resolve, reject) => {
uni.getSavedFileList({
success: (res) => {
const totalSize = res.fileList.reduce((sum, file) => sum + file.size, 0)
const totalSizeMB = (totalSize / 1024 / 1024).toFixed(2)
console.log('总文件大小', totalSizeMB, 'MB')
resolve({
fileList: res.fileList,
totalSize: totalSize,
totalSizeMB: totalSizeMB
})
},
fail: (err) => {
reject(err)
}
})
})
}
// 使用
getTotalFileSize().then(result => {
console.log('文件统计', result)
})示例 4: 清理旧文件
function cleanOldFiles(maxAge = 7 * 24 * 60 * 60 * 1000) {
// maxAge: 最大保留时间(毫秒),默认7天
uni.getSavedFileList({
success: (res) => {
const now = Date.now()
let deletedCount = 0
res.fileList.forEach(file => {
if (now - file.createTime > maxAge) {
uni.removeSavedFile({
filePath: file.filePath,
success: () => {
deletedCount++
console.log('已删除旧文件', file.filePath)
}
})
}
})
setTimeout(() => {
uni.showToast({
title: `已清理${deletedCount}个文件`,
icon: 'success'
})
}, 1000)
}
})
}
// 使用:清理7天前的文件
cleanOldFiles()示例 5: 文件管理
<template>
<view class="container">
<view class="header">
<text>文件管理</text>
<text class="total-size">总大小:{{ totalSizeMB }}MB</text>
</view>
<view class="file-list">
<view
v-for="(file, index) in fileList"
:key="index"
class="file-item"
>
<view class="file-info">
<text class="file-name">{{ getFileName(file.filePath) }}</text>
<text class="file-detail">{{ formatFileSize(file.size) }} · {{ formatTime(file.createTime) }}</text>
</view>
<view class="file-actions">
<button size="mini" @click="previewFile(file)">预览</button>
<button size="mini" @click="removeFile(file.filePath)">删除</button>
</view>
</view>
</view>
<button @click="clearAllFiles" class="clear-btn">清空所有文件</button>
</view>
</template>
<script>
export default {
data() {
return {
fileList: [],
totalSizeMB: '0.00'
}
},
onLoad() {
this.getFileList()
},
methods: {
getFileList() {
uni.getSavedFileList({
success: (res) => {
this.fileList = res.fileList
const totalSize = res.fileList.reduce((sum, file) => sum + file.size, 0)
this.totalSizeMB = (totalSize / 1024 / 1024).toFixed(2)
}
})
},
getFileName(filePath) {
return filePath.split('/').pop()
},
removeFile(filePath) {
uni.removeSavedFile({
filePath: filePath,
success: () => {
this.getFileList()
}
})
},
clearAllFiles() {
uni.showModal({
title: '确认',
content: '确定要清空所有文件吗?',
success: (res) => {
if (res.confirm) {
this.fileList.forEach(file => {
uni.removeSavedFile({
filePath: file.filePath
})
})
setTimeout(() => {
this.getFileList()
}, 500)
}
}
})
},
previewFile(file) {
// 根据文件类型预览
if (file.filePath.endsWith('.jpg') || file.filePath.endsWith('.png')) {
uni.previewImage({
urls: [file.filePath]
})
} else {
uni.showToast({
title: '暂不支持预览此类型文件',
icon: 'none'
})
}
},
formatFileSize(size) {
if (size < 1024) {
return size + ' B'
} else if (size < 1024 * 1024) {
return (size / 1024).toFixed(2) + ' KB'
} else {
return (size / 1024 / 1024).toFixed(2) + ' MB'
}
},
formatTime(timestamp) {
const date = new Date(timestamp)
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}
}
}
</script>返回值
| 参数名 | 类型 | 说明 |
|---|---|---|
| fileList | Array | 文件列表,每个文件包含 filePath、size、createTime |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ❌ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. H5 平台不支持此 API 2. 返回的文件列表包含通过 uni.saveFile 保存的文件 3. 可以通过 createTime 判断文件创建时间 4. 建议定期清理不需要的文件
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/file/file.html#getsavedfilelist
- 保存文件: https://uniapp.dcloud.net.cn/api/file/file.html#savefile
- 删除文件: https://uniapp.dcloud.net.cn/api/file/file.html#removesavedfile
uni.saveFile - 保存文件示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/file/file.html#savefile
概述
uni.saveFile 用于保存文件到本地。
基础用法
uni.saveFile({
tempFilePath: 'temp_file_path',
success: (res) => {
console.log('保存成功', res.savedFilePath)
}
})完整示例
示例 1: 保存临时文件
uni.saveFile({
tempFilePath: 'temp_file_path',
success: (res) => {
console.log('保存成功', res.savedFilePath)
uni.showToast({
title: '保存成功',
icon: 'success'
})
},
fail: (err) => {
console.error('保存失败', err)
}
})示例 2: 保存下载的文件
uni.downloadFile({
url: 'https://example.com/file.pdf',
success: (res) => {
if (res.statusCode === 200) {
// 保存下载的文件
uni.saveFile({
tempFilePath: res.tempFilePath,
success: (saveRes) => {
console.log('文件已保存', saveRes.savedFilePath)
}
})
}
}
})示例 3: 保存图片到本地
uni.chooseImage({
count: 1,
success: (res) => {
const tempFilePath = res.tempFilePaths[0]
// 保存图片
uni.saveFile({
tempFilePath: tempFilePath,
success: (saveRes) => {
console.log('图片已保存', saveRes.savedFilePath)
uni.showToast({
title: '保存成功',
icon: 'success'
})
}
})
}
})示例 4: 在页面中使用
<template>
<view class="container">
<button @click="downloadAndSave">下载并保存文件</button>
<view v-if="savedFilePath" class="file-info">
<text>文件已保存:{{ savedFilePath }}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
savedFilePath: ''
}
},
methods: {
downloadAndSave() {
uni.showLoading({
title: '下载中...'
})
uni.downloadFile({
url: 'https://example.com/file.pdf',
success: (res) => {
if (res.statusCode === 200) {
uni.saveFile({
tempFilePath: res.tempFilePath,
success: (saveRes) => {
this.savedFilePath = saveRes.savedFilePath
uni.hideLoading()
uni.showToast({
title: '保存成功',
icon: 'success'
})
},
fail: (err) => {
uni.hideLoading()
uni.showToast({
title: '保存失败',
icon: 'none'
})
}
})
}
},
fail: (err) => {
uni.hideLoading()
uni.showToast({
title: '下载失败',
icon: 'none'
})
}
})
}
}
}
</script>示例 5: 保存多个文件
function saveMultipleFiles(tempFilePaths) {
const savedFilePaths = []
let completedCount = 0
tempFilePaths.forEach((tempFilePath, index) => {
uni.saveFile({
tempFilePath: tempFilePath,
success: (res) => {
savedFilePaths[index] = res.savedFilePath
completedCount++
if (completedCount === tempFilePaths.length) {
console.log('所有文件已保存', savedFilePaths)
uni.showToast({
title: '全部保存成功',
icon: 'success'
})
}
},
fail: (err) => {
console.error(`文件${index + 1}保存失败`, err)
completedCount++
}
})
})
}
// 使用
uni.chooseImage({
count: 3,
success: (res) => {
saveMultipleFiles(res.tempFilePaths)
}
})参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| tempFilePath | String | 是 | 需要保存的文件的临时路径 |
返回值
| 参数名 | 类型 | 说明 |
|---|---|---|
| savedFilePath | String | 文件的保存路径 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ❌ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. H5 平台不支持此 API 2. 保存的文件可以通过 uni.getSavedFileList 获取列表 3. 保存的文件可以通过 uni.removeSavedFile 删除 4. 建议在保存前检查文件大小
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/file/file.html#savefile
- 获取文件列表: https://uniapp.dcloud.net.cn/api/file/file.html#getsavedfilelist
- 删除文件: https://uniapp.dcloud.net.cn/api/file/file.html#removesavedfile
uni.chooseLocation - 选择位置示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/location/choose-location.html#chooselocation
概述
uni.chooseLocation 用于打开地图选择位置。
基础用法
uni.chooseLocation({
success: (res) => {
console.log('选择的位置', res.name, res.address)
}
})完整示例
示例 1: 基本选择位置
uni.chooseLocation({
success: (res) => {
console.log('位置名称', res.name)
console.log('详细地址', res.address)
console.log('纬度', res.latitude)
console.log('经度', res.longitude)
},
fail: (err) => {
console.error('选择失败', err)
}
})示例 2: 在页面中使用
<template>
<view class="container">
<button @click="chooseLocation">选择位置</button>
<view v-if="location" class="location-info">
<text>位置:{{ location.name }}</text>
<text>地址:{{ location.address }}</text>
<text>坐标:{{ location.latitude }}, {{ location.longitude }}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
location: null
}
},
methods: {
chooseLocation() {
uni.chooseLocation({
success: (res) => {
this.location = res
uni.showToast({
title: '选择成功',
icon: 'success'
})
},
fail: (err) => {
if (err.errMsg.includes('auth deny')) {
uni.showModal({
title: '提示',
content: '需要位置权限才能选择位置',
success: (modalRes) => {
if (modalRes.confirm) {
uni.openSetting()
}
}
})
} else {
uni.showToast({
title: '选择失败',
icon: 'none'
})
}
}
})
}
}
}
</script>示例 3: 选择收货地址
<template>
<view class="container">
<view class="address-item" @click="chooseAddress">
<view v-if="address">
<text class="address-name">{{ address.name }}</text>
<text class="address-detail">{{ address.address }}</text>
</view>
<view v-else>
<text>请选择收货地址</text>
</view>
<text class="arrow">></text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
address: null
}
},
methods: {
chooseAddress() {
uni.chooseLocation({
success: (res) => {
this.address = {
name: res.name,
address: res.address,
latitude: res.latitude,
longitude: res.longitude
}
// 保存地址
uni.setStorageSync('deliveryAddress', this.address)
}
})
}
},
onLoad() {
// 加载保存的地址
const savedAddress = uni.getStorageSync('deliveryAddress')
if (savedAddress) {
this.address = savedAddress
}
}
}
</script>
<style>
.address-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
border-bottom: 1px solid #eee;
}
.address-name {
display: block;
font-size: 32rpx;
font-weight: bold;
margin-bottom: 10rpx;
}
.address-detail {
display: block;
font-size: 28rpx;
color: #999;
}
.arrow {
color: #999;
}
</style>示例 4: 检查权限
function chooseLocationWithPermission() {
// 先检查权限
uni.getSetting({
success: (res) => {
if (res.authSetting['scope.userLocation']) {
// 已授权,直接选择
chooseLocation()
} else {
// 请求授权
uni.authorize({
scope: 'scope.userLocation',
success: () => {
chooseLocation()
},
fail: () => {
uni.showModal({
title: '提示',
content: '需要位置权限才能选择位置',
success: (modalRes) => {
if (modalRes.confirm) {
uni.openSetting()
}
}
})
}
})
}
}
})
}
function chooseLocation() {
uni.chooseLocation({
success: (res) => {
console.log('选择的位置', res)
}
})
}示例 5: 在地图上显示选择的位置
<template>
<view class="container">
<button @click="chooseLocation">选择位置</button>
<map
v-if="location"
:latitude="location.latitude"
:longitude="location.longitude"
:markers="markers"
class="map"
></map>
</view>
</template>
<script>
export default {
data() {
return {
location: null,
markers: []
}
},
methods: {
chooseLocation() {
uni.chooseLocation({
success: (res) => {
this.location = res
this.markers = [{
id: 1,
latitude: res.latitude,
longitude: res.longitude,
title: res.name
}]
}
})
}
}
}
</script>
<style>
.map {
width: 100%;
height: 500px;
margin-top: 20px;
}
</style>返回值
| 参数名 | 类型 | 说明 |
|---|---|---|
| name | String | 位置名称 |
| address | String | 详细地址 |
| latitude | Number | 纬度 |
| longitude | Number | 经度 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ❌ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. 需要用户授权位置权限 2. H5 平台不支持此 API 3. 选择的位置包含名称、地址和坐标信息 4. 建议在需要时再请求权限
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/location/choose-location.html#chooselocation
- 获取位置: https://uniapp.dcloud.net.cn/api/location/location.html#getlocation
- 打开地图: https://uniapp.dcloud.net.cn/api/location/open-location.html#openlocation
uni.getLocation - 获取位置示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/location/location.html#getlocation
概述
uni.getLocation 用于获取当前地理位置。
基础用法
uni.getLocation({
type: 'wgs84',
success: (res) => {
console.log('当前位置', res.latitude, res.longitude)
}
})完整示例
示例 1: 获取当前位置
uni.getLocation({
type: 'wgs84',
success: (res) => {
console.log('纬度', res.latitude)
console.log('经度', res.longitude)
console.log('速度', res.speed)
console.log('精度', res.accuracy)
},
fail: (err) => {
console.error('获取位置失败', err)
}
})示例 2: 高精度定位
uni.getLocation({
type: 'gcj02',
altitude: true,
geocode: true,
success: (res) => {
console.log('位置信息', res)
// res.address 包含地址信息(需要 geocode: true)
}
})示例 3: 在页面中使用
<template>
<view class="container">
<button @click="getCurrentLocation">获取当前位置</button>
<view v-if="location" class="location-info">
<text>纬度:{{ location.latitude }}</text>
<text>经度:{{ location.longitude }}</text>
<text>地址:{{ location.address || '未获取' }}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
location: null
}
},
methods: {
getCurrentLocation() {
uni.showLoading({
title: '定位中...'
})
uni.getLocation({
type: 'gcj02',
geocode: true,
success: (res) => {
this.location = res
uni.hideLoading()
uni.showToast({
title: '定位成功',
icon: 'success'
})
},
fail: (err) => {
uni.hideLoading()
uni.showToast({
title: '定位失败',
icon: 'none'
})
console.error('定位失败', err)
}
})
}
}
}
</script>示例 4: 检查定位权限
// 先检查定位权限
uni.getSetting({
success: (res) => {
if (res.authSetting['scope.userLocation']) {
// 已授权,直接获取位置
uni.getLocation({
type: 'gcj02',
success: (res) => {
console.log('位置', res)
}
})
} else {
// 未授权,请求授权
uni.authorize({
scope: 'scope.userLocation',
success: () => {
uni.getLocation({
type: 'gcj02',
success: (res) => {
console.log('位置', res)
}
})
},
fail: () => {
uni.showModal({
title: '提示',
content: '需要定位权限才能使用此功能',
showCancel: false
})
}
})
}
}
})示例 5: 在地图上显示位置
<template>
<view class="container">
<button @click="getLocationAndShow">获取位置并显示</button>
<map
v-if="location"
:latitude="location.latitude"
:longitude="location.longitude"
:markers="markers"
class="map"
></map>
</view>
</template>
<script>
export default {
data() {
return {
location: null,
markers: []
}
},
methods: {
getLocationAndShow() {
uni.getLocation({
type: 'gcj02',
success: (res) => {
this.location = res
this.markers = [{
id: 1,
latitude: res.latitude,
longitude: res.longitude,
title: '我的位置'
}]
}
})
}
}
}
</script>
<style>
.map {
width: 100%;
height: 500px;
margin-top: 20px;
}
</style>参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| type | String | 否 | 坐标类型,可选值:wgs84、gcj02 |
| altitude | Boolean | 否 | 是否返回高度信息 |
| geocode | Boolean | 否 | 是否解析地址信息 |
返回值
| 参数名 | 类型 | 说明 |
|---|---|---|
| latitude | Number | 纬度 |
| longitude | Number | 经度 |
| speed | Number | 速度 |
| accuracy | Number | 位置的精确度 |
| altitude | Number | 高度(需要 altitude: true) |
| address | Object | 地址信息(需要 geocode: true) |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅(需要 HTTPS) |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. 需要用户授权定位权限 2. H5 平台需要 HTTPS 协议 3. type 为 gcj02 时返回的坐标可用于地图显示 4. geocode 为 true 时才能获取地址信息
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/location/location.html#getlocation
- 打开地图: https://uniapp.dcloud.net.cn/api/location/location.html#openlocation
- 选择位置: https://uniapp.dcloud.net.cn/api/location/location.html#chooselocation
uni.openLocation - 打开地图查看位置示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/location/open-location.html#openlocation
概述
uni.openLocation 用于使用地图查看位置,可以打开系统地图应用显示指定位置。
基础用法
uni.openLocation({
latitude: 39.908823,
longitude: 116.397470,
name: '天安门',
address: '北京市东城区'
})完整示例
示例 1: 打开地图查看位置
uni.openLocation({
latitude: 39.908823,
longitude: 116.397470,
name: '天安门',
address: '北京市东城区天安门广场',
scale: 18,
success: () => {
console.log('打开地图成功')
},
fail: (err) => {
console.error('打开地图失败', err)
}
})示例 2: 先获取位置再打开地图
// 先获取当前位置
uni.getLocation({
type: 'gcj02',
success: (locationRes) => {
// 打开地图显示当前位置
uni.openLocation({
latitude: locationRes.latitude,
longitude: locationRes.longitude,
name: '我的位置',
address: locationRes.address || '当前位置'
})
}
})示例 3: 在页面中使用
<template>
<view class="container">
<button @click="openCurrentLocation">查看当前位置</button>
<button @click="openTargetLocation">查看目标位置</button>
</view>
</template>
<script>
export default {
data() {
return {
targetLocation: {
latitude: 39.908823,
longitude: 116.397470,
name: '天安门',
address: '北京市东城区天安门广场'
}
}
},
methods: {
openCurrentLocation() {
uni.getLocation({
type: 'gcj02',
success: (res) => {
uni.openLocation({
latitude: res.latitude,
longitude: res.longitude,
name: '我的位置',
address: res.address || '当前位置'
})
},
fail: () => {
uni.showToast({
title: '获取位置失败',
icon: 'none'
})
}
})
},
openTargetLocation() {
uni.openLocation({
latitude: this.targetLocation.latitude,
longitude: this.targetLocation.longitude,
name: this.targetLocation.name,
address: this.targetLocation.address
})
}
}
}
</script>示例 4: 查看商家位置
function openStoreLocation(store) {
uni.openLocation({
latitude: store.latitude,
longitude: store.longitude,
name: store.name,
address: store.address,
scale: 18,
success: () => {
console.log('打开商家位置成功')
}
})
}
// 使用
const store = {
name: '星巴克咖啡',
address: '北京市朝阳区xxx路xxx号',
latitude: 39.908823,
longitude: 116.397470
}
openStoreLocation(store)示例 5: 导航到位置
// 在某些平台上,openLocation 可以用于导航
uni.openLocation({
latitude: 39.908823,
longitude: 116.397470,
name: '目的地',
address: '北京市东城区',
scale: 18
})参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| latitude | Number | 是 | 纬度,范围为 -90~90,负数表示南纬 |
| longitude | Number | 是 | 经度,范围为 -180~180,负数表示西经 |
| scale | Number | 否 | 缩放比例,范围 5~18,默认为 18 |
| name | String | 否 | 位置名称 |
| address | String | 否 | 地址的详细说明 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. 需要使用 gcj02 类型的坐标(通过 uni.getLocation 获取) 2. scale 值越大,地图显示越详细 3. name 和 address 用于在地图上显示位置信息 4. 不同平台打开的地图应用可能不同
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/location/open-location.html#openlocation
- 获取位置: https://uniapp.dcloud.net.cn/api/location/location.html#getlocation
uni.chooseImage - 选择图片示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/media/image.html#chooseimage
概述
uni.chooseImage 用于从本地相册选择图片或使用相机拍照。
基础用法
uni.chooseImage({
count: 1,
success: (res) => {
console.log('选择的图片', res.tempFilePaths)
}
})完整示例
示例 1: 选择单张图片
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
console.log('选择的图片路径', res.tempFilePaths)
console.log('图片文件信息', res.tempFiles)
}
})示例 2: 选择多张图片
uni.chooseImage({
count: 9, // 最多选择9张
sizeType: ['compressed'], // 只选择压缩图
sourceType: ['album'], // 只从相册选择
success: (res) => {
console.log('选择了', res.tempFilePaths.length, '张图片')
res.tempFilePaths.forEach((path, index) => {
console.log(`图片${index + 1}:`, path)
})
}
})示例 3: 在页面中使用
<template>
<view class="container">
<button @click="chooseImage">选择图片</button>
<view class="image-list">
<image
v-for="(item, index) in imageList"
:key="index"
:src="item"
mode="aspectFill"
class="image-item"
@click="previewImage(index)"
></image>
</view>
</view>
</template>
<script>
export default {
data() {
return {
imageList: []
}
},
methods: {
chooseImage() {
uni.chooseImage({
count: 9,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
this.imageList = res.tempFilePaths
uni.showToast({
title: `选择了${res.tempFilePaths.length}张图片`,
icon: 'success'
})
},
fail: (err) => {
uni.showToast({
title: '选择图片失败',
icon: 'none'
})
}
})
},
previewImage(index) {
uni.previewImage({
current: index,
urls: this.imageList
})
}
}
}
</script>
<style>
.image-list {
display: flex;
flex-wrap: wrap;
margin-top: 20px;
}
.image-item {
width: 200rpx;
height: 200rpx;
margin: 10rpx;
border-radius: 8rpx;
}
</style>示例 4: 上传图片
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
const tempFilePath = res.tempFilePaths[0]
// 上传图片
uni.uploadFile({
url: 'https://api.example.com/upload',
filePath: tempFilePath,
name: 'file',
success: (uploadRes) => {
const data = JSON.parse(uploadRes.data)
console.log('上传成功', data.url)
uni.showToast({
title: '上传成功',
icon: 'success'
})
},
fail: (err) => {
console.error('上传失败', err)
uni.showToast({
title: '上传失败',
icon: 'none'
})
}
})
}
})示例 5: 获取图片信息
uni.chooseImage({
count: 1,
success: (res) => {
const tempFilePath = res.tempFilePaths[0]
// 获取图片信息
uni.getImageInfo({
src: tempFilePath,
success: (imageInfo) => {
console.log('图片宽度', imageInfo.width)
console.log('图片高度', imageInfo.height)
console.log('图片路径', imageInfo.path)
}
})
}
})参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| count | Number | 否 | 最多可以选择的图片张数,默认 9 |
| sizeType | Array | 否 | 所选的图片的尺寸,可选值:original(原图)、compressed(压缩图) |
| sourceType | Array | 否 | 选择图片的来源,可选值:album(相册)、camera(相机) |
返回值
| 参数名 | 类型 | 说明 |
|---|---|---|
| tempFilePaths | Array | 图片的本地文件路径列表 |
| tempFiles | Array | 图片的本地文件列表,每个文件包含 path 和 size |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. 选择的图片是临时文件,需要上传到服务器才能永久保存 2. 临时文件路径在不同平台格式可能不同 3. 选择图片需要用户授权,首次使用会弹出授权提示 4. 建议使用压缩图以节省存储空间
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/media/image.html#chooseimage
- 预览图片: https://uniapp.dcloud.net.cn/api/media/image.html#previewimage
- 上传文件: https://uniapp.dcloud.net.cn/api/request/network-file.html#uploadfile
uni.chooseMedia - 选择媒体文件示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/media/video.html#choosemedia
概述
uni.chooseMedia 用于从本地相册选择图片或视频,或者使用相机拍摄图片或视频。
基础用法
uni.chooseMedia({
count: 9,
success: (res) => {
console.log('选择的文件', res.tempFiles)
}
})完整示例
示例 1: 选择图片和视频
uni.chooseMedia({
count: 9,
mediaType: ['image', 'video'],
sourceType: ['album', 'camera'],
success: (res) => {
console.log('选择的文件', res.tempFiles)
res.tempFiles.forEach((file, index) => {
console.log(`文件${index + 1}:`, file.tempFilePath)
if (file.fileType === 'image') {
console.log('图片大小', file.size)
} else if (file.fileType === 'video') {
console.log('视频时长', file.duration)
}
})
}
})示例 2: 只选择图片
uni.chooseMedia({
count: 9,
mediaType: ['image'],
sourceType: ['album', 'camera'],
sizeType: ['original', 'compressed'],
success: (res) => {
console.log('选择的图片', res.tempFiles)
}
})示例 3: 只选择视频
uni.chooseMedia({
count: 1,
mediaType: ['video'],
sourceType: ['album', 'camera'],
maxDuration: 60,
camera: 'back',
success: (res) => {
console.log('选择的视频', res.tempFiles)
}
})示例 4: 在页面中使用
<template>
<view class="container">
<button @click="chooseMedia">选择媒体文件</button>
<view class="media-list">
<view
v-for="(item, index) in mediaList"
:key="index"
class="media-item"
>
<image
v-if="item.fileType === 'image'"
:src="item.tempFilePath"
mode="aspectFill"
class="media-preview"
></image>
<video
v-else-if="item.fileType === 'video'"
:src="item.tempFilePath"
controls
class="media-preview"
></video>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
mediaList: []
}
},
methods: {
chooseMedia() {
uni.chooseMedia({
count: 9,
mediaType: ['image', 'video'],
sourceType: ['album', 'camera'],
success: (res) => {
this.mediaList = res.tempFiles
uni.showToast({
title: `选择了${res.tempFiles.length}个文件`,
icon: 'success'
})
},
fail: (err) => {
console.error('选择失败', err)
}
})
}
}
}
</script>
<style>
.media-list {
display: flex;
flex-wrap: wrap;
margin-top: 20px;
}
.media-item {
width: 200rpx;
height: 200rpx;
margin: 10rpx;
border-radius: 8rpx;
overflow: hidden;
}
.media-preview {
width: 100%;
height: 100%;
}
</style>示例 5: 上传媒体文件
uni.chooseMedia({
count: 9,
mediaType: ['image', 'video'],
success: (res) => {
const files = res.tempFiles
let uploadCount = 0
files.forEach((file, index) => {
uni.uploadFile({
url: 'https://api.example.com/upload',
filePath: file.tempFilePath,
name: 'file',
formData: {
fileType: file.fileType,
size: file.size
},
success: (uploadRes) => {
uploadCount++
console.log(`文件${index + 1}上传成功`)
if (uploadCount === files.length) {
uni.showToast({
title: '全部上传成功',
icon: 'success'
})
}
},
fail: (err) => {
console.error(`文件${index + 1}上传失败`, err)
}
})
})
}
})参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| count | Number | 否 | 最多可以选择的文件个数,默认 9 |
| mediaType | Array | 否 | 文件类型,可选值:image、video |
| sourceType | Array | 否 | 选择文件来源,可选值:album、camera |
| maxDuration | Number | 否 | 拍摄视频最长拍摄时间,单位秒 |
| camera | String | 否 | 使用前置或后置摄像头,可选值:back、front |
返回值
| 参数名 | 类型 | 说明 |
|---|---|---|
| tempFiles | Array | 选中的文件列表,每个文件包含 tempFilePath、size、fileType 等 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. mediaType 可以同时选择图片和视频 2. count 表示最多可以选择的文件个数 3. 返回的文件包含 fileType 字段,用于区分图片和视频 4. 建议根据实际需求设置 maxDuration 限制视频时长
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/media/video.html#choosemedia
- 选择图片: https://uniapp.dcloud.net.cn/api/media/image.html#chooseimage
- 选择视频: https://uniapp.dcloud.net.cn/api/media/video.html#choosevideo
uni.chooseVideo - 选择视频示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/media/video.html#choosevideo
概述
uni.chooseVideo 用于从本地相册选择视频或使用相机拍摄视频。
基础用法
uni.chooseVideo({
success: (res) => {
console.log('选择的视频', res.tempFilePath)
}
})完整示例
示例 1: 选择视频
uni.chooseVideo({
sourceType: ['album', 'camera'],
maxDuration: 60,
camera: 'back',
success: (res) => {
console.log('视频路径', res.tempFilePath)
console.log('视频时长', res.duration, '秒')
console.log('视频大小', res.size, '字节')
console.log('视频高度', res.height)
console.log('视频宽度', res.width)
}
})示例 2: 拍摄视频
uni.chooseVideo({
sourceType: ['camera'],
maxDuration: 30,
camera: 'back',
success: (res) => {
console.log('拍摄的视频', res.tempFilePath)
// 可以预览或上传视频
}
})示例 3: 在页面中使用
<template>
<view class="container">
<button @click="chooseVideo">选择视频</button>
<button @click="recordVideo">拍摄视频</button>
<video
v-if="videoSrc"
:src="videoSrc"
controls
class="video-player"
></video>
</view>
</template>
<script>
export default {
data() {
return {
videoSrc: ''
}
},
methods: {
chooseVideo() {
uni.chooseVideo({
sourceType: ['album'],
maxDuration: 60,
success: (res) => {
this.videoSrc = res.tempFilePath
uni.showToast({
title: '选择成功',
icon: 'success'
})
},
fail: (err) => {
uni.showToast({
title: '选择失败',
icon: 'none'
})
}
})
},
recordVideo() {
uni.chooseVideo({
sourceType: ['camera'],
maxDuration: 30,
camera: 'back',
success: (res) => {
this.videoSrc = res.tempFilePath
uni.showToast({
title: '拍摄成功',
icon: 'success'
})
}
})
}
}
}
</script>
<style>
.video-player {
width: 100%;
height: 400px;
margin-top: 20px;
}
</style>示例 4: 上传视频
uni.chooseVideo({
sourceType: ['album', 'camera'],
maxDuration: 60,
success: (res) => {
const tempFilePath = res.tempFilePath
// 上传视频
uni.uploadFile({
url: 'https://api.example.com/upload-video',
filePath: tempFilePath,
name: 'video',
formData: {
duration: res.duration,
size: res.size
},
success: (uploadRes) => {
const data = JSON.parse(uploadRes.data)
console.log('上传成功', data.url)
uni.showToast({
title: '上传成功',
icon: 'success'
})
},
fail: (err) => {
console.error('上传失败', err)
}
})
}
})示例 5: 限制视频时长和大小
uni.chooseVideo({
sourceType: ['album', 'camera'],
maxDuration: 30, // 最长30秒
success: (res) => {
// 检查视频大小(例如限制为50MB)
const maxSize = 50 * 1024 * 1024 // 50MB
if (res.size > maxSize) {
uni.showModal({
title: '提示',
content: '视频文件过大,请选择小于50MB的视频',
showCancel: false
})
return
}
// 检查视频时长
if (res.duration > 30) {
uni.showModal({
title: '提示',
content: '视频时长不能超过30秒',
showCancel: false
})
return
}
console.log('视频符合要求', res)
}
})参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| sourceType | Array | 否 | 选择视频的来源,可选值:album(相册)、camera(相机) |
| maxDuration | Number | 否 | 拍摄视频最长拍摄时间,单位秒 |
| camera | String | 否 | 使用前置或后置摄像头,可选值:back、front |
返回值
| 参数名 | 类型 | 说明 |
|---|---|---|
| tempFilePath | String | 选定视频的临时文件路径 |
| duration | Number | 选定视频的时间长度,单位秒 |
| size | Number | 选定视频的数据量大小,单位字节 |
| width | Number | 选定视频的宽度,单位 px |
| height | Number | 选定视频的高度,单位 px |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. 选择的视频是临时文件,需要上传到服务器才能永久保存 2. maxDuration 用于限制拍摄时长 3. 可以通过 size 检查视频文件大小 4. 建议在拍摄前提示用户视频时长限制
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/media/video.html#choosevideo
- 上传文件: https://uniapp.dcloud.net.cn/api/request/network-file.html#uploadfile
uni.getImageInfo - 获取图片信息示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/media/image.html#getimageinfo
概述
uni.getImageInfo 用于获取图片信息,包括宽度、高度、路径等。
基础用法
uni.getImageInfo({
src: 'https://example.com/image.jpg',
success: (res) => {
console.log('图片宽度', res.width)
console.log('图片高度', res.height)
}
})完整示例
示例 1: 获取网络图片信息
uni.getImageInfo({
src: 'https://example.com/image.jpg',
success: (res) => {
console.log('图片宽度', res.width)
console.log('图片高度', res.height)
console.log('图片路径', res.path)
},
fail: (err) => {
console.error('获取失败', err)
}
})示例 2: 获取本地图片信息
// 先选择图片
uni.chooseImage({
count: 1,
success: (res) => {
const tempFilePath = res.tempFilePaths[0]
// 获取图片信息
uni.getImageInfo({
src: tempFilePath,
success: (imageInfo) => {
console.log('图片信息', imageInfo)
// { width: 800, height: 600, path: '...' }
}
})
}
})示例 3: 在页面中使用
<template>
<view class="container">
<button @click="selectAndGetInfo">选择图片并获取信息</button>
<view v-if="imageInfo" class="info">
<text>宽度:{{ imageInfo.width }}px</text>
<text>高度:{{ imageInfo.height }}px</text>
<image :src="imageInfo.path" mode="aspectFit" class="preview"></image>
</view>
</view>
</template>
<script>
export default {
data() {
return {
imageInfo: null
}
},
methods: {
selectAndGetInfo() {
uni.chooseImage({
count: 1,
success: (res) => {
const tempFilePath = res.tempFilePaths[0]
uni.getImageInfo({
src: tempFilePath,
success: (imageInfo) => {
this.imageInfo = imageInfo
},
fail: (err) => {
uni.showToast({
title: '获取图片信息失败',
icon: 'none'
})
}
})
}
})
}
}
}
</script>
<style>
.info {
margin-top: 20px;
padding: 20px;
}
.preview {
width: 100%;
max-height: 400px;
margin-top: 20px;
}
</style>示例 4: 计算图片宽高比
uni.getImageInfo({
src: 'https://example.com/image.jpg',
success: (res) => {
const aspectRatio = res.width / res.height
console.log('宽高比', aspectRatio)
// 根据宽高比调整显示
if (aspectRatio > 1) {
console.log('横向图片')
} else {
console.log('纵向图片')
}
}
})示例 5: 验证图片尺寸
function validateImageSize(imagePath, minWidth, minHeight) {
return new Promise((resolve, reject) => {
uni.getImageInfo({
src: imagePath,
success: (res) => {
if (res.width >= minWidth && res.height >= minHeight) {
resolve(res)
} else {
reject(new Error(`图片尺寸不符合要求,需要至少 ${minWidth}x${minHeight}`))
}
},
fail: (err) => {
reject(err)
}
})
})
}
// 使用
validateImageSize('https://example.com/image.jpg', 800, 600)
.then(info => {
console.log('图片符合要求', info)
})
.catch(err => {
console.error('验证失败', err)
})参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| src | String | 是 | 图片的路径,可以是相对路径、临时文件路径或网络图片路径 |
返回值
| 参数名 | 类型 | 说明 |
|---|---|---|
| width | Number | 图片宽度,单位 px |
| height | Number | 图片高度,单位 px |
| path | String | 返回图片的本地路径 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. 网络图片需要配置合法域名 2. 本地图片路径需要使用 /static/ 开头或临时文件路径 3. 获取图片信息是异步操作 4. 可以用于验证图片尺寸、计算宽高比等
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/media/image.html#getimageinfo
- 选择图片: https://uniapp.dcloud.net.cn/api/media/image.html#chooseimage
uni.previewImage - 预览图片示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/media/image.html#previewimage
概述
uni.previewImage 用于预览图片,支持缩放、滑动查看多张图片。
基础用法
uni.previewImage({
urls: ['https://example.com/image1.jpg'],
current: 0
})完整示例
示例 1: 预览单张图片
uni.previewImage({
urls: ['https://example.com/image1.jpg'],
current: 'https://example.com/image1.jpg'
})示例 2: 预览多张图片
const imageList = [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg'
]
uni.previewImage({
urls: imageList,
current: 0 // 从第一张开始
})示例 3: 在页面中使用
<template>
<view class="container">
<view class="image-list">
<image
v-for="(item, index) in imageList"
:key="index"
:src="item"
mode="aspectFill"
class="image-item"
@click="previewImage(index)"
></image>
</view>
</view>
</template>
<script>
export default {
data() {
return {
imageList: [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg'
]
}
},
methods: {
previewImage(index) {
uni.previewImage({
urls: this.imageList,
current: index
})
}
}
}
</script>
<style>
.image-list {
display: flex;
flex-wrap: wrap;
}
.image-item {
width: 200rpx;
height: 200rpx;
margin: 10rpx;
border-radius: 8rpx;
}
</style>示例 4: 从选择图片到预览
<template>
<view class="container">
<button @click="chooseAndPreview">选择并预览图片</button>
<view class="image-list">
<image
v-for="(item, index) in selectedImages"
:key="index"
:src="item"
mode="aspectFill"
class="image-item"
@click="previewSelected(index)"
></image>
</view>
</view>
</template>
<script>
export default {
data() {
return {
selectedImages: []
}
},
methods: {
chooseAndPreview() {
uni.chooseImage({
count: 9,
success: (res) => {
this.selectedImages = res.tempFilePaths
// 预览第一张
if (res.tempFilePaths.length > 0) {
uni.previewImage({
urls: res.tempFilePaths,
current: 0
})
}
}
})
},
previewSelected(index) {
uni.previewImage({
urls: this.selectedImages,
current: index
})
}
}
}
</script>示例 5: 长按保存图片
<template>
<view class="container">
<image
:src="imageUrl"
mode="aspectFit"
@longpress="saveImage"
class="preview-image"
></image>
</view>
</template>
<script>
export default {
data() {
return {
imageUrl: 'https://example.com/image.jpg'
}
},
methods: {
saveImage() {
uni.showActionSheet({
itemList: ['保存图片'],
success: (res) => {
if (res.tapIndex === 0) {
uni.downloadFile({
url: this.imageUrl,
success: (downloadRes) => {
uni.saveImageToPhotosAlbum({
filePath: downloadRes.tempFilePath,
success: () => {
uni.showToast({
title: '保存成功',
icon: 'success'
})
}
})
}
})
}
}
})
}
}
}
</script>参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| urls | Array | 是 | 需要预览的图片 http 链接列表 |
| current | String/Number | 否 | 当前显示图片的索引或链接 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. urls 必须是网络图片或已下载的本地路径 2. current 可以是索引(Number)或图片链接(String) 3. 预览时支持手势缩放和滑动切换 4. 建议使用网络图片时确保图片可访问
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/media/image.html#previewimage
- 选择图片: https://uniapp.dcloud.net.cn/api/media/image.html#chooseimage
uni.saveImageToPhotosAlbum - 保存图片到相册示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/media/image.html#saveimagetophotosalbum
概述
uni.saveImageToPhotosAlbum 用于保存图片到系统相册。
基础用法
uni.saveImageToPhotosAlbum({
filePath: '/tmp/image.jpg',
success: () => {
console.log('保存成功')
}
})完整示例
示例 1: 保存网络图片
// 先下载图片
uni.downloadFile({
url: 'https://example.com/image.jpg',
success: (res) => {
if (res.statusCode === 200) {
// 保存到相册
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
uni.showToast({
title: '保存成功',
icon: 'success'
})
},
fail: (err) => {
console.error('保存失败', err)
if (err.errMsg.includes('auth deny')) {
uni.showModal({
title: '提示',
content: '需要相册权限才能保存图片',
showCancel: false
})
}
}
})
}
}
})示例 2: 保存选择的图片
uni.chooseImage({
count: 1,
success: (res) => {
const tempFilePath = res.tempFilePaths[0]
uni.saveImageToPhotosAlbum({
filePath: tempFilePath,
success: () => {
uni.showToast({
title: '保存成功',
icon: 'success'
})
},
fail: (err) => {
console.error('保存失败', err)
}
})
}
})示例 3: 在页面中使用
<template>
<view class="container">
<image :src="imageUrl" mode="aspectFit" class="preview-image"></image>
<button @click="saveImage">保存图片</button>
</view>
</template>
<script>
export default {
data() {
return {
imageUrl: 'https://example.com/image.jpg'
}
},
methods: {
saveImage() {
// 先下载图片
uni.downloadFile({
url: this.imageUrl,
success: (res) => {
if (res.statusCode === 200) {
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
uni.showToast({
title: '保存成功',
icon: 'success'
})
},
fail: (err) => {
if (err.errMsg.includes('auth deny')) {
uni.showModal({
title: '提示',
content: '需要相册权限,请在设置中开启',
success: (modalRes) => {
if (modalRes.confirm) {
uni.openSetting()
}
}
})
} else {
uni.showToast({
title: '保存失败',
icon: 'none'
})
}
}
})
}
}
})
}
}
}
</script>示例 4: 检查权限
function saveImageWithPermission(filePath) {
// 先检查权限
uni.getSetting({
success: (res) => {
if (res.authSetting['scope.writePhotosAlbum']) {
// 已授权,直接保存
saveImage(filePath)
} else {
// 请求授权
uni.authorize({
scope: 'scope.writePhotosAlbum',
success: () => {
saveImage(filePath)
},
fail: () => {
uni.showModal({
title: '提示',
content: '需要相册权限才能保存图片',
success: (modalRes) => {
if (modalRes.confirm) {
uni.openSetting()
}
}
})
}
})
}
}
})
}
function saveImage(filePath) {
uni.saveImageToPhotosAlbum({
filePath: filePath,
success: () => {
uni.showToast({
title: '保存成功',
icon: 'success'
})
}
})
}示例 5: 长按保存图片
<template>
<view class="container">
<image
:src="imageUrl"
mode="aspectFit"
@longpress="handleLongPress"
class="preview-image"
></image>
</view>
</template>
<script>
export default {
data() {
return {
imageUrl: 'https://example.com/image.jpg'
}
},
methods: {
handleLongPress() {
uni.showActionSheet({
itemList: ['保存图片'],
success: (res) => {
if (res.tapIndex === 0) {
this.saveImage()
}
}
})
},
saveImage() {
uni.downloadFile({
url: this.imageUrl,
success: (res) => {
if (res.statusCode === 200) {
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
uni.showToast({
title: '保存成功',
icon: 'success'
})
}
})
}
}
})
}
}
}
</script>参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| filePath | String | 是 | 图片文件路径,可以是临时文件路径或永久文件路径 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. 需要用户授权相册权限 2. 网络图片需要先下载到本地 3. 如果权限被拒绝,可以引导用户到设置中开启 4. 建议在保存前检查权限状态
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/media/image.html#saveimagetophotosalbum
- 下载文件: https://uniapp.dcloud.net.cn/api/request/network-file.html#downloadfile
- 授权: https://uniapp.dcloud.net.cn/api/other/authorize.html#authorize
uni.navigateBack - 返回上一页示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/router.html#navigateback
概述
uni.navigateBack 用于关闭当前页面,返回上一页面或多级页面。
基础用法
uni.navigateBack()完整示例
示例 1: 基本返回
uni.navigateBack({
success: () => {
console.log('返回成功')
},
fail: (err) => {
console.error('返回失败', err)
}
})示例 2: 返回多级页面
// 返回上一页
uni.navigateBack({
delta: 1
})
// 返回上两页
uni.navigateBack({
delta: 2
})示例 3: 在页面中使用
<template>
<view class="container">
<button @click="goBack">返回</button>
<button @click="goBackTwoPages">返回上两页</button>
</view>
</template>
<script>
export default {
methods: {
goBack() {
uni.navigateBack()
},
goBackTwoPages() {
uni.navigateBack({
delta: 2
})
}
}
}
</script>示例 4: 带数据返回
<!-- 当前页面 -->
<template>
<view class="container">
<button @click="saveAndBack">保存并返回</button>
</view>
</template>
<script>
export default {
data() {
return {
formData: {
name: 'test',
value: '123'
}
}
},
methods: {
saveAndBack() {
// 保存数据到上一页
const pages = getCurrentPages()
const prevPage = pages[pages.length - 2]
if (prevPage) {
prevPage.setData({
savedData: this.formData
})
}
uni.navigateBack()
}
}
}
</script>示例 5: 返回前确认
<template>
<view class="container">
<button @click="handleBack">返回</button>
</view>
</template>
<script>
export default {
data() {
return {
hasChanges: false
}
},
methods: {
handleBack() {
if (this.hasChanges) {
uni.showModal({
title: '提示',
content: '有未保存的更改,确定要返回吗?',
success: (res) => {
if (res.confirm) {
uni.navigateBack()
}
}
})
} else {
uni.navigateBack()
}
}
}
}
</script>参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| delta | Number | 否 | 返回的页面数,如果 delta 大于现有页面数,则返回到首页 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. delta 默认为 1,表示返回上一页 2. 如果 delta 大于现有页面数,会返回到首页 3. 可以通过 getCurrentPages() 获取页面栈信息 4. 返回时可以传递数据给上一页
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/router.html#navigateback
- 页面跳转: https://uniapp.dcloud.net.cn/api/router.html#navigateto
uni.navigateTo - 页面跳转示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/router.html#navigateto
概述
uni.navigateTo 用于保留当前页面,跳转到应用内的某个页面。
基础用法
uni.navigateTo({
url: '/pages/detail/detail'
})完整示例
示例 1: 基本跳转
uni.navigateTo({
url: '/pages/detail/detail',
success: () => {
console.log('跳转成功')
},
fail: (err) => {
console.error('跳转失败', err)
}
})示例 2: 带参数跳转
// 跳转并传递参数
uni.navigateTo({
url: '/pages/detail/detail?id=123&name=test'
})
// 在目标页面接收参数
// pages/detail/detail.vue
export default {
onLoad(options) {
console.log('接收到的参数', options)
// { id: '123', name: 'test' }
}
}示例 3: 传递对象参数
// 传递对象
const params = {
id: 123,
name: 'test',
data: { key: 'value' }
}
// 需要序列化
uni.navigateTo({
url: `/pages/detail/detail?data=${encodeURIComponent(JSON.stringify(params))}`
})
// 在目标页面解析
export default {
onLoad(options) {
const data = JSON.parse(decodeURIComponent(options.data))
console.log('解析后的数据', data)
}
}示例 4: 在组件中使用
<template>
<view class="container">
<button @click="goToDetail">查看详情</button>
<button @click="goToDetailWithParams">带参数跳转</button>
</view>
</template>
<script>
export default {
methods: {
goToDetail() {
uni.navigateTo({
url: '/pages/detail/detail'
})
},
goToDetailWithParams() {
uni.navigateTo({
url: '/pages/detail/detail?id=123&name=test'
})
}
}
}
</script>示例 5: 封装跳转函数
// utils/navigation.js
const navigation = {
// 跳转到详情页
toDetail(id) {
uni.navigateTo({
url: `/pages/detail/detail?id=${id}`
})
},
// 跳转到用户页
toUser(userId) {
uni.navigateTo({
url: `/pages/user/user?id=${userId}`
})
},
// 通用跳转
navigate(url, params = {}) {
const query = Object.keys(params)
.map(key => `${key}=${encodeURIComponent(params[key])}`)
.join('&')
const fullUrl = query ? `${url}?${query}` : url
uni.navigateTo({
url: fullUrl
})
}
}
// 使用
navigation.toDetail(123)
navigation.navigate('/pages/detail/detail', { id: 123, name: 'test' })注意事项
1. 不能跳转到 tabBar 页面,需要使用 uni.switchTab 2. 路径前需要加 /,表示从根目录开始 3. 参数会拼接在 URL 后面,长度有限制 4. 复杂对象需要序列化后传递
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/router.html#navigateto
- 其他路由 API: https://uniapp.dcloud.net.cn/api/router.html
uni.reLaunch - 重新启动应用示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/router.html#relaunch
概述
uni.reLaunch 用于关闭所有页面,打开到应用内的某个页面。
基础用法
uni.reLaunch({
url: '/pages/index/index'
})完整示例
示例 1: 基本重新启动
uni.reLaunch({
url: '/pages/index/index',
success: () => {
console.log('重新启动成功')
},
fail: (err) => {
console.error('重新启动失败', err)
}
})示例 2: 退出登录后重新启动
function logout() {
// 清除所有数据
uni.clearStorageSync()
// 重新启动到登录页
uni.reLaunch({
url: '/pages/login/login'
})
}示例 3: 在页面中使用
<template>
<view class="container">
<button @click="restartApp">重新启动应用</button>
</view>
</template>
<script>
export default {
methods: {
restartApp() {
uni.showModal({
title: '提示',
content: '确定要重新启动应用吗?',
success: (res) => {
if (res.confirm) {
uni.reLaunch({
url: '/pages/index/index'
})
}
}
})
}
}
}
</script>示例 4: 与 navigateTo 和 redirectTo 的区别
// navigateTo: 保留当前页面,可以返回
uni.navigateTo({
url: '/pages/detail/detail'
})
// 页面栈: [首页, 详情页]
// redirectTo: 关闭当前页面,不能返回
uni.redirectTo({
url: '/pages/detail/detail'
})
// 页面栈: [详情页] (首页被关闭)
// reLaunch: 关闭所有页面,重新启动
uni.reLaunch({
url: '/pages/detail/detail'
})
// 页面栈: [详情页] (所有页面都被关闭)示例 5: 登录后重新启动
function login() {
uni.request({
url: 'https://api.example.com/login',
method: 'POST',
data: { username: 'test', password: '123456' },
success: (res) => {
if (res.data.success) {
uni.setStorageSync('token', res.data.token)
// 重新启动到首页
uni.reLaunch({
url: '/pages/index/index'
})
}
}
})
}参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| url | String | 是 | 需要跳转的应用内非 tabBar 的页面的路径 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. 不能跳转到 tabBar 页面,需要使用 uni.switchTab 2. 会关闭所有页面,无法返回 3. 路径前需要加 /,表示从根目录开始 4. 适合退出登录、重新启动等场景
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/router.html#relaunch
- 页面跳转: https://uniapp.dcloud.net.cn/api/router.html#navigateto
uni.redirectTo - 重定向跳转示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/router.html#redirectto
概述
uni.redirectTo 用于关闭当前页面,跳转到应用内的某个页面。
基础用法
uni.redirectTo({
url: '/pages/detail/detail'
})完整示例
示例 1: 基本重定向
uni.redirectTo({
url: '/pages/detail/detail',
success: () => {
console.log('跳转成功')
},
fail: (err) => {
console.error('跳转失败', err)
}
})示例 2: 带参数重定向
uni.redirectTo({
url: '/pages/detail/detail?id=123&name=test'
})
// 在目标页面接收参数
// pages/detail/detail.vue
export default {
onLoad(options) {
console.log('接收到的参数', options)
// { id: '123', name: 'test' }
}
}示例 3: 登录后重定向
function login() {
// 登录逻辑
uni.request({
url: 'https://api.example.com/login',
method: 'POST',
data: { username: 'test', password: '123456' },
success: (res) => {
if (res.data.success) {
// 保存 token
uni.setStorageSync('token', res.data.token)
// 重定向到首页(关闭登录页)
uni.redirectTo({
url: '/pages/index/index'
})
}
}
})
}示例 4: 在页面中使用
<template>
<view class="container">
<button @click="goToDetail">跳转到详情页</button>
</view>
</template>
<script>
export default {
methods: {
goToDetail() {
uni.redirectTo({
url: '/pages/detail/detail?id=123'
})
}
}
}
</script>示例 5: 与 navigateTo 的区别
// navigateTo: 保留当前页面,可以返回
uni.navigateTo({
url: '/pages/detail/detail'
})
// 页面栈: [首页, 详情页]
// redirectTo: 关闭当前页面,不能返回
uni.redirectTo({
url: '/pages/detail/detail'
})
// 页面栈: [详情页] (首页被关闭)参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| url | String | 是 | 需要跳转的应用内非 tabBar 的页面的路径 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. 不能跳转到 tabBar 页面,需要使用 uni.switchTab 2. 会关闭当前页面,无法返回 3. 路径前需要加 /,表示从根目录开始 4. 适合登录后跳转等不需要返回的场景
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/router.html#redirectto
- 保留页面跳转: https://uniapp.dcloud.net.cn/api/router.html#navigateto
- 重新启动: https://uniapp.dcloud.net.cn/api/router.html#relaunch
uni.switchTab - 切换 TabBar 页面示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/router.html#switchtab
概述
uni.switchTab 用于跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面。
基础用法
uni.switchTab({
url: '/pages/index/index'
})完整示例
示例 1: 基本切换
uni.switchTab({
url: '/pages/index/index',
success: () => {
console.log('切换成功')
},
fail: (err) => {
console.error('切换失败', err)
}
})示例 2: 在页面中使用
<template>
<view class="container">
<button @click="goToHome">回到首页</button>
<button @click="goToCategory">分类</button>
<button @click="goToCart">购物车</button>
<button @click="goToProfile">我的</button>
</view>
</template>
<script>
export default {
methods: {
goToHome() {
uni.switchTab({
url: '/pages/index/index'
})
},
goToCategory() {
uni.switchTab({
url: '/pages/category/category'
})
},
goToCart() {
uni.switchTab({
url: '/pages/cart/cart'
})
},
goToProfile() {
uni.switchTab({
url: '/pages/profile/profile'
})
}
}
}
</script>示例 3: 登录后跳转到首页
function login() {
uni.request({
url: 'https://api.example.com/login',
method: 'POST',
data: { username: 'test', password: '123456' },
success: (res) => {
if (res.data.success) {
uni.setStorageSync('token', res.data.token)
// 跳转到 tabBar 首页
uni.switchTab({
url: '/pages/index/index'
})
}
}
})
}示例 4: 封装切换函数
// utils/navigation.js
const navigation = {
switchToTab(url) {
uni.switchTab({
url: url,
fail: (err) => {
console.error('切换失败', err)
// 如果不是 tabBar 页面,使用 navigateTo
uni.navigateTo({
url: url
})
}
})
}
}
// 使用
navigation.switchToTab('/pages/index/index')参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| url | String | 是 | 需要跳转的 tabBar 页面的路径 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. 只能跳转到 pages.json 中配置的 tabBar 页面 2. 不能传递参数(URL 参数会被忽略) 3. 会关闭所有非 tabBar 页面 4. 如果目标页面不是 tabBar 页面,会触发 fail 回调
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/router.html#switchtab
- 页面跳转: https://uniapp.dcloud.net.cn/api/router.html#navigateto
uni.downloadFile - 下载文件示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/request/network-file.html#downloadfile
概述
uni.downloadFile 用于下载文件资源到本地。
基础用法
uni.downloadFile({
url: 'https://example.com/file.pdf',
success: (res) => {
console.log('下载成功', res.tempFilePath)
}
})完整示例
示例 1: 下载图片
uni.downloadFile({
url: 'https://example.com/image.jpg',
success: (res) => {
if (res.statusCode === 200) {
console.log('下载成功', res.tempFilePath)
// 可以预览或保存图片
uni.previewImage({
urls: [res.tempFilePath]
})
}
},
fail: (err) => {
console.error('下载失败', err)
}
})示例 2: 下载并保存到相册
uni.downloadFile({
url: 'https://example.com/image.jpg',
success: (res) => {
if (res.statusCode === 200) {
// 保存到相册
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
uni.showToast({
title: '保存成功',
icon: 'success'
})
},
fail: (err) => {
console.error('保存失败', err)
}
})
}
}
})示例 3: 显示下载进度
uni.downloadFile({
url: 'https://example.com/large-file.pdf',
success: (res) => {
console.log('下载完成', res.tempFilePath)
},
fail: (err) => {
console.error('下载失败', err)
}
})示例 4: 在页面中使用
<template>
<view class="container">
<button @click="downloadFile">下载文件</button>
<view v-if="downloading" class="download-status">
<text>下载中...</text>
</view>
<view v-if="filePath" class="file-info">
<text>文件路径:{{ filePath }}</text>
<button @click="openFile">打开文件</button>
</view>
</view>
</template>
<script>
export default {
data() {
return {
downloading: false,
filePath: ''
}
},
methods: {
downloadFile() {
this.downloading = true
uni.downloadFile({
url: 'https://example.com/file.pdf',
success: (res) => {
if (res.statusCode === 200) {
this.filePath = res.tempFilePath
this.downloading = false
uni.showToast({
title: '下载成功',
icon: 'success'
})
}
},
fail: (err) => {
this.downloading = false
uni.showToast({
title: '下载失败',
icon: 'none'
})
}
})
},
openFile() {
// 打开文件
uni.openDocument({
filePath: this.filePath,
success: () => {
console.log('打开成功')
}
})
}
}
}
</script>示例 5: 封装下载函数
// utils/download.js
const download = {
downloadFile(url, options = {}) {
return new Promise((resolve, reject) => {
uni.downloadFile({
url: url,
header: options.header || {},
success: (res) => {
if (res.statusCode === 200) {
resolve(res.tempFilePath)
} else {
reject(new Error(`下载失败,状态码:${res.statusCode}`))
}
},
fail: (err) => {
reject(err)
}
})
})
},
async downloadAndSave(url) {
try {
const filePath = await this.downloadFile(url)
// 根据文件类型保存
if (filePath.endsWith('.jpg') || filePath.endsWith('.png')) {
await uni.saveImageToPhotosAlbum({ filePath })
} else {
await uni.saveFile({ tempFilePath: filePath })
}
return filePath
} catch (err) {
throw err
}
}
}
// 使用
download.downloadFile('https://example.com/file.pdf')
.then(filePath => {
console.log('下载成功', filePath)
})
.catch(err => {
console.error('下载失败', err)
})参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| url | String | 是 | 下载资源的 url |
| header | Object | 否 | HTTP 请求 Header |
返回值
| 参数名 | 类型 | 说明 |
|---|---|---|
| tempFilePath | String | 临时文件路径,下载后的文件会存储到一个临时文件 |
| statusCode | Number | HTTP 状态码 |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. 下载的文件是临时文件,需要保存才能永久使用 2. 可以通过 statusCode 判断下载是否成功 3. 下载的文件路径是临时路径,应用关闭后可能失效 4. 建议下载后立即保存或使用
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/request/network-file.html#downloadfile
- 保存文件: https://uniapp.dcloud.net.cn/api/file/file.html#savefile
- 打开文档: https://uniapp.dcloud.net.cn/api/file/file.html#opendocument
uni.request - 网络请求示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/request/request.html
概述
uni.request 用于发起网络请求,支持 GET、POST、PUT、DELETE 等方法。
基础用法
GET 请求
uni.request({
url: 'https://api.example.com/data',
method: 'GET',
success: (res) => {
console.log('请求成功', res.data)
},
fail: (err) => {
console.error('请求失败', err)
}
})POST 请求
uni.request({
url: 'https://api.example.com/user',
method: 'POST',
data: {
name: 'John',
age: 30
},
header: {
'Content-Type': 'application/json'
},
success: (res) => {
console.log('请求成功', res.data)
}
})完整示例
示例 1: 带参数的 GET 请求
uni.request({
url: 'https://api.example.com/users',
method: 'GET',
data: {
page: 1,
limit: 10
},
success: (res) => {
if (res.statusCode === 200) {
console.log('用户列表', res.data)
}
},
fail: (err) => {
uni.showToast({
title: '请求失败',
icon: 'none'
})
}
})示例 2: POST 请求上传数据
uni.request({
url: 'https://api.example.com/users',
method: 'POST',
data: {
name: 'John Doe',
email: 'john@example.com',
age: 30
},
header: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
},
success: (res) => {
if (res.statusCode === 200 || res.statusCode === 201) {
uni.showToast({
title: '创建成功',
icon: 'success'
})
}
}
})示例 3: 使用 Promise
// Promise 方式(部分平台支持)
uni.request({
url: 'https://api.example.com/data'
}).then(res => {
console.log('请求成功', res.data)
}).catch(err => {
console.error('请求失败', err)
})示例 4: 封装请求函数
// utils/request.js
const request = (options) => {
return new Promise((resolve, reject) => {
uni.request({
url: options.url,
method: options.method || 'GET',
data: options.data || {},
header: {
'Content-Type': 'application/json',
...options.header
},
success: (res) => {
if (res.statusCode === 200) {
resolve(res.data)
} else {
reject(new Error(`请求失败: ${res.statusCode}`))
}
},
fail: (err) => {
reject(err)
}
})
})
}
// 使用
request({
url: 'https://api.example.com/data',
method: 'GET'
}).then(data => {
console.log('数据', data)
}).catch(err => {
console.error('错误', err)
})示例 5: 请求拦截和响应拦截
// utils/http.js
const baseURL = 'https://api.example.com'
// 请求拦截
const requestInterceptor = (config) => {
// 添加 token
const token = uni.getStorageSync('token')
if (token) {
config.header = {
...config.header,
'Authorization': `Bearer ${token}`
}
}
return config
}
// 响应拦截
const responseInterceptor = (res) => {
if (res.statusCode === 401) {
// token 过期,跳转登录
uni.navigateTo({
url: '/pages/login/login'
})
return Promise.reject(new Error('未授权'))
}
return res.data
}
const http = {
request(options) {
const config = requestInterceptor({
url: baseURL + options.url,
method: options.method || 'GET',
data: options.data || {},
header: options.header || {}
})
return new Promise((resolve, reject) => {
uni.request({
...config,
success: (res) => {
try {
const data = responseInterceptor(res)
resolve(data)
} catch (err) {
reject(err)
}
},
fail: (err) => {
reject(err)
}
})
})
}
}
export default http示例 6: 超时处理
uni.request({
url: 'https://api.example.com/data',
method: 'GET',
timeout: 5000, // 5秒超时
success: (res) => {
console.log('请求成功', res.data)
},
fail: (err) => {
if (err.errMsg && err.errMsg.includes('timeout')) {
uni.showToast({
title: '请求超时',
icon: 'none'
})
} else {
uni.showToast({
title: '请求失败',
icon: 'none'
})
}
}
})示例 7: 处理不同数据类型
// JSON 数据
uni.request({
url: 'https://api.example.com/data',
dataType: 'json',
success: (res) => {
console.log('JSON 数据', res.data)
}
})
// 文本数据
uni.request({
url: 'https://api.example.com/text',
dataType: 'text',
success: (res) => {
console.log('文本数据', res.data)
}
})
// ArrayBuffer 数据
uni.request({
url: 'https://api.example.com/binary',
responseType: 'arraybuffer',
success: (res) => {
console.log('二进制数据', res.data)
}
})平台差异
- H5: 支持
withCredentials参数,用于跨域请求携带凭证 - App: 支持
sslVerify参数,用于验证 SSL 证书 - App: 支持
firstIpv4参数,DNS 解析时优先使用 IPv4
注意事项
1. 默认超时时间为 60000ms(60秒) 2. 默认 dataType 为 json,会自动解析 JSON 数据 3. 请求 header 中不能设置 Referer 4. 部分平台支持 Promise 方式调用 5. 建议封装统一的请求函数,便于统一处理错误和拦截
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/request/request.html
- 网络请求最佳实践: https://uniapp.dcloud.net.cn/api/request/request.html
uni.clearStorage - 清除所有存储数据示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/storage/storage.html#clearstorage
概述
uni.clearStorage 用于清理本地数据缓存,清除所有存储的数据。
基础用法
uni.clearStorage({
success: () => {
console.log('清除成功')
}
})完整示例
示例 1: 清除所有数据
uni.clearStorage({
success: () => {
console.log('所有数据已清除')
uni.showToast({
title: '清除成功',
icon: 'success'
})
},
fail: (err) => {
console.error('清除失败', err)
}
})示例 2: 退出登录时清除
function logout() {
uni.clearStorage({
success: () => {
console.log('数据已清除')
// 跳转到登录页
uni.reLaunch({
url: '/pages/login/login'
})
}
})
}示例 3: 在页面中使用
<template>
<view class="container">
<button @click="clearAllData">清除所有数据</button>
</view>
</template>
<script>
export default {
methods: {
clearAllData() {
uni.showModal({
title: '提示',
content: '确定要清除所有数据吗?此操作不可恢复',
success: (res) => {
if (res.confirm) {
uni.clearStorage({
success: () => {
uni.showToast({
title: '清除成功',
icon: 'success'
})
// 重新加载页面
setTimeout(() => {
uni.reLaunch({
url: '/pages/index/index'
})
}, 1500)
}
})
}
}
})
}
}
}
</script>示例 4: 同步版本
try {
uni.clearStorageSync()
console.log('清除成功')
} catch (err) {
console.error('清除失败', err)
}参数说明
此 API 无需参数。
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. 此操作会清除所有本地存储的数据,请谨慎使用 2. 建议在清除前提示用户确认 3. 同步版本 clearStorageSync 性能更好 4. 清除后可能需要重新登录或初始化数据
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/storage/storage.html#clearstorage
- 同步版本: https://uniapp.dcloud.net.cn/api/storage/storage.html#clearstoragesync
- 删除单个: https://uniapp.dcloud.net.cn/api/storage/storage.html#removestorage
uni.removeStorage - 删除存储数据示例
官方文档
参考官方文档:https://uniapp.dcloud.net.cn/api/storage/storage.html#removestorage
概述
uni.removeStorage 用于从本地缓存中异步移除指定 key。
基础用法
uni.removeStorage({
key: 'userInfo',
success: () => {
console.log('删除成功')
}
})完整示例
示例 1: 删除单个数据
uni.removeStorage({
key: 'token',
success: () => {
console.log('Token 已删除')
},
fail: (err) => {
console.error('删除失败', err)
}
})示例 2: 退出登录时清除数据
function logout() {
// 删除用户信息
uni.removeStorage({
key: 'userInfo',
success: () => {
console.log('用户信息已清除')
}
})
// 删除 Token
uni.removeStorage({
key: 'token',
success: () => {
console.log('Token 已清除')
// 跳转到登录页
uni.reLaunch({
url: '/pages/login/login'
})
}
})
}示例 3: 批量删除
const keysToRemove = ['userInfo', 'token', 'settings']
keysToRemove.forEach(key => {
uni.removeStorage({
key: key,
success: () => {
console.log(`${key} 已删除`)
}
})
})示例 4: 在页面中使用
<template>
<view class="container">
<button @click="clearUserData">清除用户数据</button>
<button @click="clearAllData">清除所有数据</button>
</view>
</template>
<script>
export default {
methods: {
clearUserData() {
uni.removeStorage({
key: 'userInfo',
success: () => {
uni.showToast({
title: '用户数据已清除',
icon: 'success'
})
}
})
},
clearAllData() {
uni.clearStorage({
success: () => {
uni.showToast({
title: '所有数据已清除',
icon: 'success'
})
}
})
}
}
}
</script>示例 5: 同步版本
try {
uni.removeStorageSync('userInfo')
console.log('删除成功')
} catch (err) {
console.error('删除失败', err)
}参数说明
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| key | String | 是 | 本地缓存中指定的 key |
平台兼容性
| 平台 | 支持情况 |
|---|---|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
注意事项
1. 如果 key 不存在,不会报错 2. 建议使用同步版本 removeStorageSync 性能更好 3. 删除操作是异步的,需要等待 success 回调 4. 退出登录时建议清除所有相关数据
参考资源
- 官方文档: https://uniapp.dcloud.net.cn/api/storage/storage.html#removestorage
- 同步版本: https://uniapp.dcloud.net.cn/api/storage/storage.html#removestoragesync
- 清除所有: https://uniapp.dcloud.net.cn/api/storage/storage.html#clearstorage