界面常用 API
1. 设置导航栏
js
// 设置导航栏颜色
uni.setNavigationBarColor({
frontColor: this.hasSetBg ? "#000000" : "#ffffff",
backgroundColor: this.hasSetBg ? "#F8F8F8" : "#007AFF"
})
// 设置导航栏内容
uni.setNavigationBarTitle({
title: this.hasSetText ? "Hello uni-app" : "默认导航栏"
})
2. 跳转
js
// 跳转到指定页面(相对路径),并传递数据
uni.navigateTo({
url: 'new-page/new-vue-page-1?data=Hello'
})
// 返回上一层
uni.navigateBack()
// 在当前页面打开
uni.redirectTo({
url: 'new-page/new-vue-page-1'
})
// 切换选项卡
uni.switchTab({
url: '/pages/tabBar/template/template'
})
// 关闭所有页面,并打开首页
uni.reLaunch({
url: '/pages/component/view/view'
})
// 使用自定义动画打开(只有 APP+ 支持)
uni.navigateTo({
url: 'new-page/new-vue-page-1?data=anim',
animationType: 'slide-in-bottom',
animationDuration: 200
})
接收传递的数据,在跳转页面写 onLoad()
函数
js
onLoad(options) {
console.log('页面参数:', options)
}
3. 设置 TabBar 样式
js
// 设置 TabBar 样式
uni.setTabBarStyle({
color: '#7A7E83',
selectedColor: '#007AFF',
backgroundColor: '#F8F8F8',
borderStyle: 'black'
})
// 显示红点
uni.showTabBarRedDot({
index: 1
})
// 隐藏红点
uni.hideTabBarRedDot({
index: 1
})
// 显示角标
uni.setTabBarBadge({
index: 1,
text: '1'
})
// 隐藏角标
uni.removeTabBarBadge({
index: 1
})
// 显示 TabBar
uni.showTabBar()
// 隐藏 TabBar
uni.hideTabBar()
// 自定义 TabBar 信息
uni.setTabBarItem({
index: 1,
text: '接口',
iconPath: '/static/api.png',
selectedIconPath: '/static/apiHL.png'
})
4. 下拉刷新
js
// 下拉刷新事件
onPullDownRefresh() {
console.log('onPullDownRefresh')
}
5. 创建动画
xml
<view class="animation-element"
:animation="animationData"></view>
js
// 数据域
data() {
return {
animationData: ''
}
}
// 创建动画对象
onLoad() {
this.animation = uni.createAnimation()
}
// 卸载事件
onUnload(){
this.animationData = ''
}
// 全部同时展示
function all() {
this.animation.rotate(Math.random() * 720 - 360)
.scale(Math.random() * 2)
.translate(Math.random() * 100 - 50,
Math.random() * 100 - 50)
.skew(Math.random() * 90, Math.random() * 90)
.step()
this.animationData = this.animation.export()
}
// 按顺序展示
function allInQueue() {
this.animation.rotate(Math.random() * 720 - 360).step()
.scale(Math.random() * 2).step()
.translate(Math.random() * 100 - 50,
Math.random() * 100 - 50).step()
.skew(Math.random() * 90, Math.random() * 90).step()
this.animationData = this.animation.export()
}
6. 创建绘图
xml
<canvas class="canvas-element" canvas-id="canvas"
id="canvas"></canvas>
js
// context 在 export default {} 的外层
var context = null
// 绑定到 context
onReady() {
context = uni.createCanvasContext('canvas', this)
}
// 绘制图像
function drawImage() {
// #ifdef APP-PLUS
context.drawImage(
'../../../static/app-plus/uni@2x.png', 0, 0)
// #endif
// #ifndef APP-PLUS
context.drawImage('../../../static/uni.png', 0, 0)
// #endif
context.draw()
}
// 绘制内容
function scale() {
context.beginPath()
context.rect(25, 25, 50, 50)
context.stroke()
context.scale(2, 2)
context.beginPath()
context.rect(25, 25, 50, 50)
context.stroke()
context.draw()
}
7. 节点信息
xml
<!-- 头条小程序不支持 -->
<!-- #ifndef MP-TOUTIAO -->
<movable-area>
<movable-view class="target" direction="all"
@change="getNodeInfo">Drag
</movable-view>
</movable-area>
<!-- #endif -->
js
getNodeInfo() {
uni.createSelectorQuery().select(
'.target').boundingClientRect().exec((ret) => {
const rect = ret[0]
if (rect) {
const sort = [
'left','right','top','bottom','width','height'
]
const info = []
for (let i in sort) {
let key = sort[i]
info.push({
'key': key,
'val': rect[key]
})
}
this.info = info
}
})
}
8. 节点布局交互状态
js
let observer = null
export default {
data() {
return {
appear: false,
title: 'intersectionObserver'
}
},
onReady() {
observer = uni.createIntersectionObserver(this)
observer.relativeTo('.scroll-view').observe(
'.ball', (res) => {
if (res.intersectionRatio > 0 && !this.appear) {
this.appear = true
} else if (!res.intersectionRatio > 0 &&
this.appear) {
this.appear = false
}
})
},
onUnload() {
if (observer) {
observer.disconnect()
}
}
}
9. 显示操作菜单
js
// 测试:H5 上有 bug(移动后不能跟随),H5 的移动端表现良好
// #ifdef H5
onReady() {
this.getNodeInfo()
window.addEventListener('resize', this.getNodeInfo)
}
beforeDestroy() {
window.removeEventListener('resize', this.getNodeInfo)
}
// #endif
actionSheetTap() {
const that = this
uni.showActionSheet({
title: '标题',
itemList: ['item1', 'item2', 'item3', 'item4'],
popover: {
// 104: navbar + topwindow 高度
top: that.buttonRect.top + 104 +
that.buttonRect.height,
left: that.buttonRect.left +
that.buttonRect.width / 2
},
success: (e) => {
console.log(e.tapIndex)
uni.showToast({
title: "点击了第" + e.tapIndex + "个选项",
icon: "none"
})
}
})
}
// #ifdef H5
getNodeInfo() {
uni.createSelectorQuery().select(
'.target').boundingClientRect().exec((ret) => {
const rect = ret[0]
if (rect) {
this.buttonRect = rect
}
})
}
// #endif
10. 模态弹窗
js
// 有标题的
uni.showModal({
title: "弹窗标题",
content: "弹窗内容,告知当前状态、信息和解决方法",
showCancel: false,
confirmText: "确定"
})
// 没有标题的
uni.showModal({
content: "弹窗内容,告知当前状态、信息和解决方法",
confirmText: "确定",
cancelText: "取消"
})
11. 加载提示框
js
uni.showLoading({
title: 'loading'
})
// #ifdef MP-ALIPAY
this._showTimer && clearTimeout(this._showTimer)
this._showTimer = setTimeout(() => {
this.hideLoading()
}, 3000)
// #endif
12. 显示消息提示框
js
// 默认消息框,默认 1500 ms
uni.showToast({
title: "默认"
})
// 设置延时
uni.showToast({
title: "duration 3000",
duration: 3000
})
// 加载动画(支付宝小程序不支持)
uni.showToast({
title: "loading",
icon: "loading",
duration: 5000
})
// 点击显示无图标的居底 toast(只有 APP+ 支持)
uni.showToast({
title: "显示一段轻提示",
position:'bottom'
})
// 隐藏
uni.hideToast()
设备和网络
1. 网络状态
html
<!-- 微信支持获取 WiFi 信息 -->
<!-- #ifdef MP-WEIXIN -->
<button v-if="hasNetworkType === true && networkType === 'wifi'"
class="uni-common-mt" type="primary"
@tap="getConnectedWifi">获取 wifi 信息</button>
<!-- #endif -->
js
uni.getNetworkType({
success: (res) => {
console.log(res)
this.hasNetworkType = true
this.networkType = res.subtype || res.networkType
},
fail: () => {
uni.showModal({
content:'获取失败!',
showCancel:false
})
}
})
// #ifdef MP-WEIXIN
getConnectedWifi() {
const that = this
uni.startWifi({
success: function() {
uni.getConnectedWifi({
success: function(res) {
const { wifi } = res
that.connectedWifi = JSON.stringify(wifi)
},
fail: function(res) {
}
})
},
fail: function(res) {
}
})
}
// #endif
2. 系统信息
xml
<view class="uni-list">
<view class="uni-list-cell">
<view class="uni-pd">
<view class="uni-label" style="width:180px">
设备型号</view>
</view>
<view class="uni-list-cell-db">
<input class="uni-input" type="text"
:disabled="true" placeholder="未获取"
:value="systemInfo.model"/>
</view>
</view>
<view class="uni-list-cell">
<view class="uni-pd">
<view class="uni-label" style="width:180px">
客户端平台</view>
</view>
<view class="uni-list-cell-db">
<input class="uni-input" type="text"
:disabled="true" placeholder="未获取"
:value="systemInfo.platform"/>
</view>
</view>
<view class="uni-list-cell">
<view class="uni-pd">
<view class="uni-label" style="width:180px">
操作系统版本</view>
</view>
<view class="uni-list-cell-db">
<input class="uni-input" type="text"
:disabled="true" placeholder="未获取"
:value="systemInfo.system"/>
</view>
</view>
<view class="uni-list-cell">
<view class="uni-pd">
<view class="uni-label" style="width:180px">
语言</view>
</view>
<view class="uni-list-cell-db">
<input class="uni-input" type="text"
:disabled="true" placeholder="未获取"
:value="systemInfo.language"/>
</view>
</view>
<view class="uni-list-cell">
<view class="uni-pd">
<view class="uni-label" style="width:180px">
版本</view>
</view>
<view class="uni-list-cell-db">
<input class="uni-input" type="text"
:disabled="true" placeholder="未获取"
:value="systemInfo.version"/>
</view>
</view>
<view class="uni-list-cell">
<view class="uni-pd">
<view class="uni-label" style="width:180px">
屏幕宽度</view>
</view>
<view class="uni-list-cell-db">
<input class="uni-input" type="text"
:disabled="true" placeholder="未获取"
:value="systemInfo.screenWidth"/>
</view>
</view>
<view class="uni-list-cell">
<view class="uni-pd">
<view class="uni-label" style="width:180px">
屏幕高度</view>
</view>
<view class="uni-list-cell-db">
<input class="uni-input" type="text"
:disabled="true" placeholder="未获取"
:value="systemInfo.screenHeight"/>
</view>
</view>
<view class="uni-list-cell">
<view class="uni-pd">
<view class="uni-label" style="width:180px">
可使用窗口高度</view>
</view>
<view class="uni-list-cell-db">
<input class="uni-input" type="text"
:disabled="true" placeholder="未获取"
:value="systemInfo.windowHeight"/>
</view>
</view>
<view class="uni-list-cell">
<view class="uni-pd">
<view class="uni-label" style="width:180px">
可使用窗口的顶部位置</view>
</view>
<view class="uni-list-cell-db">
<input class="uni-input" type="text"
:disabled="true" placeholder="未获取"
:value="systemInfo.windowTop"/>
</view>
</view>
<view class="uni-list-cell">
<view class="uni-pd">
<view class="uni-label" style="width:180px">
可使用窗口的底部位置</view>
</view>
<view class="uni-list-cell-db">
<input class="uni-input" type="text"
:disabled="true" placeholder="未获取"
:value="systemInfo.windowBottom"/>
</view>
</view>
<view class="uni-list-cell">
<view class="uni-pd">
<view class="uni-label" style="width:180px">
状态栏的高度</view>
</view>
<view class="uni-list-cell-db">
<input class="uni-input" type="text"
:disabled="true" placeholder="未获取"
:value="systemInfo.statusBarHeight"/>
</view>
</view>
<view class="uni-list-cell">
<view class="uni-pd">
<view class="uni-label" style="width:180px">
DPI</view>
</view>
<view class="uni-list-cell-db">
<input class="uni-input" type="text"
:disabled="true" placeholder="未获取"
:value="systemInfo.pixelRatio"/>
</view>
</view>
<!-- #ifdef MP -->
<view class="uni-list-cell">
<view class="uni-pd">
<view class="uni-label" style="width:180px">
基础库版本</view>
</view>
<view class="uni-list-cell-db">
<input class="uni-input" type="text"
:disabled="true" placeholder="未获取"
:value="systemInfo.SDKVersion"/>
</view>
</view>
<!-- #endif -->
</view>
js
uni.getSystemInfo({
success: (res) => {
this.systemInfo = res
}
})
3. 打电话
js
uni.makePhoneCall({
phoneNumber: this.inputValue,
success: () => {
console.log("成功拨打电话")
}
})
4. 发送一个请求
js
uni.request({
url: requestUrl,
dataType: 'text',
data: {
noncestr: Date.now()
},
success: (res) => {
this.res = JSON.stringify(res)
},
fail: (err) => {
console.log('请求失败: ', err)
uni.showModal({
content: err.errMsg,
showCancel: false
})
},
complete: () => {
this.loading = false
}
})
Promise
和async/await
模式请求在 Vue2 和 Vue3 中有区别。 详情参考/pages/API/request
中的示例代码。
5. 上传图片
js
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album'],
success: (res) => {
console.log('chooseImage success, temp path is',
res.tempFilePaths[0])
var imageSrc = res.tempFilePaths[0]
uni.uploadFile({
url: 'https://unidemo.dcloud.net.cn/upload',
filePath: imageSrc,
fileType: 'image',
name: 'data',
success: (res) => {
console.log('uploadImage success, res is:', res)
uni.showToast({
title: '上传成功',
icon: 'success',
duration: 1000
})
this.imageSrc = imageSrc
},
fail: (err) => {
console.log('uploadImage fail', err)
uni.showModal({
content: err.errMsg,
showCancel: false
})
}
})
},
fail: (err) => {
console.log('chooseImage fail', err)
// #ifdef MP
uni.getSetting({
success: (res) => {
let authStatus = res.authSetting['scope.album']
if (!authStatus) {
uni.showModal({
title: '授权失败',
content: '请在设置界面打开相关权限',
success: (res) => {
if (res.confirm) {
uni.openSetting()
}
}
})
}
}
})
// #endif
}
})
6. 下载内容
js
var self = this
uni.downloadFile({
url: "https://demo.demo.com/demo.png",
success: (res) => {
console.log('downloadFile success, res is', res)
self.imageSrc = res.tempFilePath
uni.hideLoading()
},
fail: (err) => {
console.log('downloadFile fail, err is:', err)
}
})
其他常用功能
储存 key-val
数据
js
// 储存数据
uni.setStorage({
key: key,
data: data,
success: (res) => {
uni.showModal({
title: '存储数据成功',
content: JSON.stringify(res.errMsg),
showCancel: false
})
},
fail: () => {
uni.showModal({
title: '储存数据失败!',
showCancel: false
})
}
})
// 读取数据
uni.getStorage({
key: key,
success: (res) => {
uni.showModal({
title: '读取数据成功',
content: "data: '" + res.data + "'",
showCancel: false
})
},
fail: () => {
uni.showModal({
title: '读取数据失败',
content: "找不到 key 对应的数据",
showCancel: false
})
}
})
// 清除数据
uni.clearStorageSync()
获取当前位置
js
// APP+ 端要引入授权模块
import permision from "@/common/permission.js"
// 微信、头条、QQ 小程序要设置授权
// 地理位置授权,每一端都不一样
uni.getLocation({
success: (res) => {
this.hasLocation = true;
this.location = formatLocation(res.longitude, res.latitude);
},
fail: (err) => {
// #ifdef MP-BAIDU
// 202:模拟器 10003:真机
if (err.errCode === 202 || err.errCode === 10003) {
this.showConfirm();
}
// #endif
// #ifndef MP-BAIDU
if (err.errMsg.indexOf("auth deny") >= 0) {
uni.showToast({
title: "访问位置被拒绝"
})
} else {
uni.showToast({
title: err.errMsg
})
}
// #endif
}
})
高级参考
功能 | 参考位置 |
---|---|
复杂页面预加载 | /pages/API/navigator/navigator |
页面上传、使用图片 | /pages/API/image/image |
页面上传、使用视频 | /pages/API/video/video |
页面上传、使用音频 | /pages/API/inner-audio/inner-audio |
地图控制 | /pages/API/map/map |
使用地图选择位置 | /pages/API/choose-location/choose-location |
使用地图查看位置 | /pages/API/open-location/open-location |
使用 WebSocket 任务 | /pages/API/websocket-socketTask/websocket-socketTask |
全局 WebSocket | /pages/API/websocket-global/websocket-global |