位置相关
涉及到地图 App平台 manifest中配置好自己的地图厂商key,在地图厂商的后台,填写正确包名和证书摘要
- App平台 manifest中配置好自己的地图厂商key,在地图厂商的后台,填写正确包名和证书摘要。地图厂商的sdk会在运行时校验key、包名、证书的一致性
- Web平台 manifest中配置好自己的地图厂商key,使用web接口如涉及白名单,需确保自己的域名在地图厂商那里正确配置了域名白名单
- 确保在地图厂商那里配额足够
- 确保在地图厂商那里有周边服务的权限。否则无法获取周围地址
如果运行在微信浏览器中,可以使用微信的jssdk的定位能力。这个是微信向腾讯地图申请的key,开发者无需配置自己的key。
地图厂商的商业授权较贵,如需购买,请点击获取优惠
uni.getLocation
uni.getLocation({
type: 'wgs84',
success: function (res) {
console.log('当前位置的经度:' + res.longitude);
console.log('当前位置的纬度:' + res.latitude);
}
});
uni.chooseLocation
uni.chooseLocation({
success: function (res) {
console.log('位置名称:' + res.name);
console.log('详细地址:' + res.address);
console.log('纬度:' + res.latitude);
console.log('经度:' + res.longitude);
}
});
这两个api前面有介绍地址选点的注意事项,这里不在赘述~请移步快速开始那篇文章
媒体相关
uni.chooseImage
从本地相册选择图片或使用相机拍照。微信小程序从基础库 2.21.0 开始, wx.chooseImage 停止维护,请使用 uni.chooseMedia 代替。
uni.chooseMedia({
count: 9,
mediaType: ['image','video'],
sourceType: ['album', 'camera'],
maxDuration: 30,
camera: 'back',
success(res) {
console.log(res.tempFiles)
}
})
<template>
<view>测试页面</view>
<button type="primary" @click="test()">选择图片</button>
</template>
<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
const test = () => {
// 小程序 基础库 2.21.0 以后使用上面的 uni.chooseMedia
uni.chooseImage({
count: 6, // 最多可以选择的图片张数,默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['camera'], // album 从相册选图,camera 使用相机,默认二者都有。
success: function (res) {
console.log(JSON.stringify(res.tempFilePaths));
// 预览图片
uni.previewImage({
urls: res.tempFilePaths,
longPressActions: {
itemList: ['发送给朋友', '保存图片', '收藏'],
success: function (data) {
console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
},
fail: function (err) {
console.log(err.errMsg);
}
}
});
}
});
};
</script>
uni.saveImageToPhotosAlbum
保存图片到系统相册
- 可以通过用户授权API来判断用户是否给应用授予相册的访问权限uniapp.dcloud.io/api/other/a…
- H5没有API可触发保存到相册行为,下载图片时浏览器会询问图片存放地址。
- 微信小程序在2023年10月17日之后,使用API需要配置隐私协议
uni.chooseImage({
count: 1,
sourceType: ['camera'],
success: function (res) {
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePaths[0],
success: function () {
console.log('save success');
}
});
}
});
wx.chooseMessageFile
从客户端会话选择文件,从微信聊天会话中选择文件。
这个只能在微信小程序(基础库2.5.0+)和qq小程序(基础库1.18.0+)使用其他平台不可以使用API使用文档
wx.chooseMessageFile({
count: 10,
type: 'image',
success (res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFiles
}
})
uni.getRecorderManager()
获取全局唯一的录音管理器 recorderManager
<template>
<button @tap="startRecord">开始录音</button>
<button @tap="endRecord">停止录音</button>
<button @tap="playVoice">播放录音</button>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;
// 使用ref定义响应式数据
const voicePath = ref('');
// 定义方法
const startRecord = () => {
console.log('开始录音');
recorderManager.start();
};
const endRecord = () => {
console.log('录音结束');
recorderManager.stop();
};
const playVoice = () => {
console.log('播放录音');
if (voicePath.value) {
innerAudioContext.src = voicePath.value;
innerAudioContext.play();
}
};
onLoad((option) => {
recorderManager.onStop(function (res) {
console.log('recorder stop' + JSON.stringify(res));
voicePath.value = res.tempFilePath;
});
});
</script>
设备相关
uni.getSystemInfo
异步获取系统信息 (uni.getSystemInfoSync
同步获取)
- 屏幕高度 = 原生NavigationBar高度(含状态栏高度)+ 可使用窗口高度 + 原生TabBar高度
- windowHeight不包含NavigationBar和TabBar的高度
- Web端,windowTop等于NavigationBar高度,windowBottom等于TabBar高度
- App端,windowTop等于透明状态NavigationBar高度,windowBottom等于透明状态TabBar高度
- 高度相关信息,要放在 onReady 里获取。太早取不到
uni.getSystemInfo({
success: function (res) {
console.log(res);
}
});
uni.getNetworkType
获取网络类型
uni.getNetworkType({
success: function (res) {
console.log(res.networkType);
}
});
uni.makePhoneCall
打电话 小程序直接调用 app如下
// ios和安卓不同情况, 需要注意:手机号要为字符串
cellPhone(phone) {
const res = uni.getSystemInfoSync();
// ios系统默认有个模态框
if (res.platform == 'ios') {
uni.makePhoneCall({
phoneNumber: phone,
})
} else {
// 安卓手机手动设置一个showActionSheet
uni.showActionSheet({
itemList: ['phone', '呼叫'],
success: function(res) {
if (res.tapIndex == 1) {
uni.makePhoneCall({
phoneNumber: phone,
})
}
}
})
}
}
- Android需要在 manifest.json 增加权限
<uses-permission android:name="android.permission.CALL_PHONE"/>
- Android不弹出询问框直接拨打电话:ask.dcloud.net.cn/question/40…
- 发送短信:www.html5plus.org/doc/zh_cn/m…
- Android读取短信验证码:ask.dcloud.net.cn/article/676
- Android遍历读取短信:ask.dcloud.net.cn/article/129… 注意需要赋予相关权限。
- 钉钉小程序端拨打电话,详见open.dingtalk.com/document/or…
HarmonyOS Next
平台使用时需要添加权限ohos.permission.PLACE_CALL
uni.scanCode
调起客户端扫码界面,扫码成功后返回对应的结果。除h5不支持其他都支持
// 允许从相机和相册扫码
uni.scanCode({
success: function (res) {
console.log('条码类型:' + res.scanType);
console.log('条码内容:' + res.result);
}
});
// 只允许通过相机扫码
uni.scanCode({
onlyFromCamera: true,
success: function (res) {
console.log('条码类型:' + res.scanType);
console.log('条码内容:' + res.result);
}
});
// 调起条码扫描
uni.scanCode({
scanType: ['barCode'],
success: function (res) {
console.log('条码类型:' + res.scanType);
console.log('条码内容:' + res.result);
}
});
界面交互
uni.showToast
显示消息提示框
uni.showToast({
// 长度显示规则上面表格
title: '标题',
duration: 2000
});
uni.setNavigationBarTitle
动态设置当前页面的标题。
- 如果需要在页面进入时设置标题,可以在
onReady
内执行,以避免被框架内的修改所覆盖。如果必须在onShow
内执行需要延迟一小段时间。
uni.setNavigationBarTitle({
title: '首页111'
});
uni.setNavigationBarColor
设置页面导航条颜色。如果需要进入页面就设置颜色,请延迟执行,防止被框架内设置颜色逻辑覆盖
uni.setNavigationBarColor({
frontColor: '#ffffff',
backgroundColor: '#007aff'
});
uni.setTabBarItem
动态设置 tabBar 某一项的内容 (必须更换已有的)
uni.setTabBarItem({
index: 1,
text: '动态bar',
iconPath: 'static/logo.png',
selectedIconPath: 'static/logo.png'
});
uni.setTabBarStyle
动态设置 tabBar 的整体样式
uni.setTabBarStyle({
color: '#FF0000',
selectedColor: '#00FF00',
backgroundColor: '#0000FF',
borderStyle: 'white'
})
uni.hideTabBar
隐藏 tabBar 与之对应的 uni.showTabBar
显示 tabBar
uni.hideTabBar()
uni.setTabBarBadge
为 tabBar 某一项的右上角添加文本 图下效果,与之对应的 uni.removeTabBarBadge
移除 tabBar 某一项右上角的文本
uni.setTabBarBadge({
// 下标
index: 0,
// 文案 显示的文本,不超过 3 个半角字符
text: '1'
});
uni.showTabBarRedDot
显示 tabBar 某一项的右上角的红点,与之对应的 uni.hideTabBarRedDot
隐藏 tabBar 某一项的右上角的红点
uni.showTabBarRedDot({
index: 0
});
- tabbar是原生的,层级高于前端元素
- uni-app插件市场有封装的前端tabbar,但性能不如原生tabbar
- 如果想要一个中间带+号的tabbar,在HBuilderX中新建uni-app项目、选择 底部选项卡 模板
- 以上大部分操作 tabbar 的 API 需要在 tabbar 渲染后才能使用,避免在 tabbar 未初始化前使用
uni.pageScrollTo
将页面滚动到目标位置。可以指定滚动到具体的scrollTop数值,也可以指定滚动到某个元素的位置
uni.pageScrollTo({
scrollTop: 0,
duration: 300
});
- app-uvue支持的选择器较少,不支持ID选择器,详见
- app-uvue的页面滚动,是由页面最外层的scroll-view模拟的,如果页面最外层不是scroll-view,无法使用本api。详见
- app-uvue的scroll-view滚动时,如需动画,则需要在scroll-view的属性中配置
scroll-with-animation="true"
,详见 - scroll-view的滚动,设置其scrollTop即可。详见
uni.onWindowResize
监听窗口尺寸变化事件
const windowResizeCallback = (res) => {
console.log('变化后的窗口宽度=' + res.size.windowWidth)
console.log('变化后的窗口高度=' + res.size.windowHeight)
}
uni.onWindowResize(windowResizeCallback)
- 如App端设置软键盘弹出方式为adjustResize ,则在键盘弹出时,会触发此事件。
- 横竖屏切换时,会触发此事件
uni.offWindowResize
取消监听窗口尺寸变化事件
// `CALLBACK`为调用`uni.onWindowResize`时传入的`CALLBACK`
uni.offWindowResize(windowResizeCallback)
onPullDownRefresh
在 js 中定义 onPullDownRefresh 处理函数(和onLoad等生命周期函数同级),监听该页面用户下拉刷新事件。
- 需要在
pages.json
里,找到的当前页面的pages节点,并在style
选项中开启enablePullDownRefresh
。 - 当处理完数据刷新后,
uni.stopPullDownRefresh
可以停止当前页面的下拉刷新
uni.startPullDownRefresh
开始下拉刷新,调用后触发下拉刷新动画,效果与用户手动下拉刷新一致。
uni.stopPullDownRefresh
停止当前页面下拉刷新。
{
"pages": [
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "uni-app",
"enablePullDownRefresh": true
}
}
],
}
三个api都和下拉刷新相关
SelectorQuery
查询节点信息的对象
selectorQuery.in(component)
将选择器的选取范围更改为自定义组件 component
内,返回一个 SelectorQuery
对象实例。(初始时,选择器仅选取页面范围的节点,不会选取任何自定义组件中的节点)。
// options API 选项式 API
const query = uni.createSelectorQuery().in(this);
query
.select("#id")
.boundingClientRect((data) => {
console.log("得到布局位置信息" + JSON.stringify(data));
console.log("节点离页面顶部的距离为" + data.top);
})
.exec();
// Composition API 组合式 API
import { getCurrentInstance } from 'vue';
const instance = getCurrentInstance();
const query = uni.createSelectorQuery().in(instance.proxy);
query
.select("#id")
.boundingClientRect((data) => {
console.log("得到布局位置信息" + JSON.stringify(data));
console.log("节点离页面顶部的距离为" + data.top);
})
.exec();
selectorQuery.select(selector)
在当前页面下选择第一个匹配选择器 selector
的节点,返回一个 NodesRef
对象实例,可以用于获取节点信息。
selector 说明:
selector
类似于 CSS 的选择器,但仅支持下列语法。
- ID 选择器:
#the-id
- class 选择器(可以连续指定多个):
.a-class.another-class
- 子元素选择器:
.the-parent > .the-child
- 后代选择器:
.the-ancestor .the-descendant
- 跨自定义组件的后代选择器:
.the-ancestor >>> .the-descendant
(H5 暂不支持) - 多选择器的并集:
#a-node, .some-other-nodes
#selectorQuery.selectAll(selector)
在当前页面下选择匹配选择器 selector
的所有节点,返回一个 NodesRef
对象实例,可以用于获取节点信息。
#selectorQuery.selectViewport()
选择显示区域,可用于获取显示区域的尺寸、滚动位置等信息,返回一个 NodesRef
对象实例。
#selectorQuery.exec(callback)
执行所有的请求。请求结果按请求次序构成数组,在 callback 的第一个参数中返回。
nextTick(function callback)
在小程序自定义组件,如wxcomponents中使用。延迟一部分操作到下一个时间片再执行。(类似于 setTimeout) 。其他平台无此概念。
其他
uni.getAccountInfoSync
获取当前帐号信息,只兼容部分小程序 可以返回小程序的Appid 以及运行环境 (小程序 当前环境版本:develop
开发版、trial
体验版、release
正式版、gray
灰度版)
uni.getAccountInfoSync()
uni.navigateToMiniProgram
打开另一个小程序
uni.navigateToMiniProgram({
// 要打开的小程序 appId
appId: '',
// 打开的页面路径,如果为空则打开首页
path: 'pages/index/index?id=123',
// 需要传递给目标小程序的数据,目标小程序可在 `App.vue` 的 `onLaunch`或`onShow` 中获取到这份数据
extraData: {
'data1': 'test'
},
success(res) {
// 打开成功
}
})
uni.navigateBackMiniProgram
跳转回上一个小程序,只有当另一个小程序跳转到当前小程序时才会能调用成功。
uni.navigateBackMiniProgram({
extraData: {
'data1': 'test'
},
success(res) {
// 返回成功
}
})
Tip
- 将upx单位值转换成px。因upx(uni.upx2px())已废弃,推荐使用rpx。rpx无需特殊API可直接使用
- nvue 暂不支持
uni.createSelectorQuery
- 网络请求的
超时时间
可以统一在manifest.json
中配置 networkTimeout - H5 端本地调试需注意跨域问题,参考:调试跨域问题解决方案
- 注意小程序端不支持自动保持 cookie,服务器应避免验证 cookie。如果服务器无法修改,也可以使用一些模拟手段,比如这样的工具github.com/charleslo1/… 可以请求时带上 cookie 并将响应的 cookie 保存在本地。
- H5端 cookie 受跨域限制(和平时开发网站时一样),旧版的 uni.request 未支持
withCredentials
配置,可以直接使用 xhr 对象或者其他类库。 - 根据 W3C 规范,H5 端无法获取
response header
中Set-Cookie、Set-Cookie2
这2个字段,对于跨域请求,允许获取的response header
字段只限于“simple response header”
和“Access-Control-Expose-Headers”
(详情) - uni-app 插件市场有flyio、axios等三方封装的拦截器可用
- 使用一些比较小众的证书机构(如:CFCA OV OCA)签发的 ssl 证书在安卓设备请求会失败,因为这些机构的根证书不在系统内置根证书库,可以更换其他常见机构签发的证书(如:Let's Encrypt),或者配置 sslVerify 为 false 关闭 ssl 证书验证(不推荐)。
- 离线打包不支持
sslVerify
配置 - 单次网络请求数据量建议控制在
50K
以下(仅指json数据,不含图片),过多数据应分页获取,以提升应用体验 - 在各个小程序平台运行时,网络相关的 API 在使用前
需要配置域名白名单
- App支持多文件上传,微信小程序只支持单文件上传,传多个文件需要反复调用本API。所以跨端的写法就是循环调用本API。
- App平台打开微信小程序,使用plus.share的launchMiniProgram。注意uni-app不需要plus ready,将plus ready里的代码写到页面的onLoad生命周期即可。使用此功能需在manifest中配置微信分享SDK信息,打包后生效。
- 各小程序平台对跳转到其他小程序有一些限制和规定,需要遵守,具体见各平台文档。
- 不能在横屏下打开半屏小程序