记录一下在uniapp开发app中,检查app版本,并更新,并使用自定义弹窗,并且自定义弹窗需要覆盖原生tabbar。
思路与难点:
- 在
app.vue中请求接口,检查是否是最新版本,是最新版本就下载安装最新文件。 - 希望使用自定义弹窗组件,但是
uniapp项目中app.vue中无法引入模板,且自定义的弹窗组件无法覆盖原生的tabbar
- 解决方案:使用一个页面作为弹窗就可以覆盖
tabbr,页面透明的可设置为透明,视觉效果上就与弹窗一致了。
- 自定义的弹窗页面在如果在app首页还未加载出来时就弹出,导致弹窗的背景是空白,且如果路由正在跳转过程中也有可能被其他页面覆盖,需要等待几秒后,再弹出弹窗
代码:
page.json
- 设置弹窗页面的样式透明
- 注意不要写在pages中的第一个
{
"path": "pages/update/update", // 更新页面
"style": {
"navigationStyle": "custom",
"navigationBarTextStyle": "white",
"app-plus": {
"animationType": "fade-in",
"background": "transparent",
"backgroundColor": "transparent",
"popGesture": "none" // 关闭IOS屏幕左边滑动关闭当前页面的功能
}
}
},
app.vue
- 检查版本更新,并出自定义弹窗页面
onLaunch: function() {
// 等待页面加载完成后,再检查版本更新
setTimeout(() => {
this.checkVersion()
}, 6000)
},
methods: {
// 检查版本号
async checkVersion() {
try {
// #ifdef APP
let platformCode = this.$u.sys().platform === "android" ? '1' : '2' // android是1 ios是0
let res = await this.$api.appVersion(platformCode) // 请求后端接口
if (plus.runtime.version === res.version) return // 判断版本号是否相等
uni.navigateTo({
// 传入下载链接与是否强制更新
url: `/pages/update/update?isForce=${res.isForce}&updateUrl=${res.url}`,
})
// #endif
} catch (e) {}
},
}
update.vue
- 强制更新不能返回上一页,在onBackPress中监听返回,true不能返回,false可以返回
<template>
<!--自定义的弹窗组件,大家可以自行封装,这里就不做展示了-->
<Dialog ref="dialog" :closeOnClickOverlay="false" :iconSrc="`${$env.FILE_URL}/uniapp/home/tipfail.svg`"
:cancelBtn="cancelBtn" confirmBtn="立即下载" title="发现新版本" message="优化了更多的细节"></Dialog>
</template>
<script>
export default {
data() {
return {
cancelBtn: "", // 是否显示取消按钮
isForce: 1, // 0 不强制更新,1强制更新
updateUrl: '' // 下载链接
}
},
onLoad(options) {
this.isForce = options.isForce
this.cancelBtn = options.isForce==1 ? "" : "取消" // 强制更新不显示取消按钮
this.updateUrl = options.updateUrl
},
onBackPress() {
// 强制更新禁止返回页面
if (this.isForce==1) return true
return false
},
mounted() {
// 打开自定义弹窗,第一个参数是点击确定的回调,第二个是点击取消的回调
this.$refs.dialog.showPanel(
() => {
// 点击确定,下载新版本
this.updateAPP()
}, () => {
// 点击取消返回上一页
uni.navigateBack()
})
},
methods: {
// 更新应用
updateAPP() {
uni.showLoading({
title: '更新中……'
})
uni.downloadFile({ //执行下载
url: this.updateUrl, //下载地址
success: downloadResult => { //下载成功
if (downloadResult.statusCode == 200) {
plus.runtime.install( //安装
downloadResult.tempFilePath, {
force: true
},
() => {
uni.hideLoading();
this.$u.toast('更新成功,重启中');
plus.runtime.restart();
},
() => {
uni.hideLoading();
this.$u.toast('更新失败');
}
);
}
}
})
}
},
}
</script>
<style>
page {
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0); // 设置页面透明
}
</style>