uniapp版本升级,下载安装功能逻辑部分

页面效果如下图:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

1、把版本升级提示封装为子组件,方便随时调用,我这里用了

<script>
	export default {
		components: {},
		props: {
			//show: 加载组件,但是不弹出提示框
			show: {
				type: [Boolean],
			},
			//url: 如果是首页,不提示 已是最新版本
			url:{
				type: [String],
			}
		},
		data() {
			return {
				show2:false,//是否弹出更新提示框
				upshow: false,//是否显示进度条
				android:{},//是否更新数据,请求接口后存起来备用。
				progress:0,//下载进度
			}
		},
		watch:{
			//show:监听组件加载,判断是否需要弹出更新提示
			show(newVal,oldVal){
				if(newVal){
					let _this = this;
					this.android = JSON.parse(uni.getStorageSync('android')); // 读取版本数据
					// let version = this.android.version.split(".").join(""); // 需要更新的版本 1.0.1  === 101
					let version = 99
					plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
						let time_version = widgetInfo.versionCode;// 当前APP的版本 : 100
						if(time_version < version){ // 当前版本小于更新版本,提示更新,
							_this.show2 = true;//可以弹出更新提示框
							uni.hideTabBar();// APP 无法遮挡tabbar,直接隐藏掉
						}else{
							if(_this.url != 'index'){
								uni.showToast({
									title: "已是最新版本",
									icon:'none',
								});
							}
							_this.$emit('closeVersion');//关闭show组件
						}
						
					})
				}
			}
		},
		
		onShow() {
			
		},
		methods: {
			//升级
			up() {
				let _this = this;
				this.progress = 0;
				this.upshow = true;//切换进度条显示
				//开启下载任务
				const downloadTask = uni.downloadFile({
					url: _this.android.download_url,
					success: (res) => {
						if (res.statusCode === 200) {
							plus.runtime.install(res.tempFilePath);////下载成功安装apk
						}
					},
					fail: (err) => {
						console.log(err);
						uni.showToast({
							icon:'none',
							mask:true,
							title: '安装失败,请重新下载',
						});
						setTimeout(()=>{
							_this.close();
						},1500)
					},
					// 接口调用结束
					complete() {
						downloadTask.offProgressUpdate();//取消监听加载进度
						setTimeout(()=>{
							_this.close();
						},1500)
					}
				});
				//监听下载进度
				downloadTask.onProgressUpdate((res) => {
					_this.progress = res.progress;
				});
			},
			close() {
				this.show2 = false;//关闭更新弹窗
				this.upshow = false;//关闭进度条
				uni.showTabBar();//显示tabbar
				this.$emit('closeVersion');//关闭show组件
			}

		},
	}
</script>

猜你喜欢

转载自blog.csdn.net/qq_40745143/article/details/107282435