Actualización en caliente de Uniapp, actualización del paquete de recursos

me lo mostré a mí mismo

Dirección completa del proyecto

La dirección de descarga del código fuente, está en mi página de inicio

Conjunto completo correspondiente de enlaces de video

El conjunto completo de videos está abierto para todos, descargue el código fuente y envíeme un mensaje privado para obtener el código de extracción.
Por favor agregue una descripción de la imagen
Por favor agregue una descripción de la imagen
Por favor agregue una descripción de la imagen

1. Comunidad de preguntas y respuestas de Uniapp, primer vistazo al documento

La comunidad de preguntas y respuestas de DCloud
Por favor agregue una descripción de la imagen
utiliza principalmente este, el módulo frontal

2. Busquemos la diferencia de acuerdo a la imagen, lo mejor es crear un nuevo util.js y poner el siguiente código

	// 处理 热更新(直接复制的)
	update(showToast = false) {
		// #ifdef APP-PLUS  
		plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
			// uni.request({
			// 	url: 'https://ceshi.dishait.cn/api/v1/update',
			// 	data: {
			// 		version: widgetInfo.version,
			// 		name: widgetInfo.name
			// 	},
			$http.post('/update',{
				ver:widgetInfo.version, // 当前app版本号
			}).then((res)=>{
				// let [err,result] = await $http.post('/update',{
				// 	ver:widgetInfo.version, // 当前app版本号
				// }) 等于上面这种回调写法 
				let [err,result] = res;
				// 错误处理
				if(!$http.errorCheck(err,result)) return
				// 成功
				var data = result.data.data;
				/*
				   {  接收到到格式
						"msg": "ok",
						"data": {
							"id": 1,
							"url": "http://www.baidu.com",
							"version": "1.0.1",
							"status": 1,
							"create_time": null
						}
					}
				如果没有,url直接终止*/ 
				if(!data.url){
					// 无需更新
					if(showToast){ 
					return uni.showToast({
							title:'已经是最新版本了,无需更新',
							icon:'none'
						})
					}
				}
				// 需要更新
				uni.showModal({
					title:'发现新的版本', // 标题
					content:'最新版本'+data.version, // 内容
					cancelText:'暂不更新', // 取消
					confirmText:'立即更新', //确认
					success:(res)=>{ // 用户点击了确认
						if(res.confirm){
					    // 下载文件,uniapp官方的
						uni.downloadFile({
							url: data.url, //上面声明的成功返回的数据
							success: (downloadResult) => {
								if (downloadResult.statusCode === 200) {
									// 成功回调函数
									plus.runtime.install(downloadResult.tempFilePath, {
										force: false
									}, function() {
										console.log('install success...');
										plus.runtime.restart();
									}, function(e) {
										console.error('install fail...');
									});
								}
							}
						});	
					  }
					}
				})
			});
		});
		// #endif
	},

3. Función de manejo de errores

 // 这个是自己封装的 http请求,错误处理函数
if(!$http.errorCheck(err,result)) return 

request.js encapsula parámetros de solicitud incorrectos

// 错误处理
	errorCheck(err,res,errfun = false,resfun = false){
		if (err) {
			typeof errfun === 'function' && errfun();
			uni.showToast({ title: '加载失败',icon:"none" });
			return false;
		}
		if (res.data.errorCode) {
			typeof errfun === 'function' && resfun();
			uni.showToast({ title: res.data.msg,icon:"none" });
			return false;
		}
		return true;
	},c 

Cuelgue directamente en el prototipo en man.js, y se puede llamar globalmente

// 引入 封装api的 请求库
import $H from './common/request.js'
Vue.prototype.$H = $H

En APP.vue, simplemente llámelo y el usuario verificará la actualización de la versión tan pronto como ingrese a la aplicación

onLaunch: function() {
			console.log('App Launch');
			  // #ifdef APP-PLUS
			  // 检测更新
			   this.$U.update()
			  // #endif
			
			  // 网络监听	(调用main.js挂载的 $U函数)
			  this.$U.onNetWork()
		},

La página de detección de versión es la siguiente about.vue

<!-- 关于社区页面 -->
<template>
	<view>
		<view class="flex align-center justify-center flex-column pt-4 pb-3">
			<image
				src="/static/demo/datapic/6.jpg"
				mode="left"
				style="width: 300rpx;height: 300rpx;"
				class="rounded-circle"
			></image>
			<!-- #ifdef APP-PLUS -->
			<text class="font text-muted mt-2"> version {
   
   {version}}</text>
			<!-- #endif -->
		</view>
		<!-- #ifdef APP-PLUS -->
		<uni-list-item title="新版本检测" clickable showArrow @click="update"></uni-list-item>
		<!-- #endif -->
		<uni-list-item title="社区用户协议" clickable showArrow></uni-list-item>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 动态改变版本号
				version: '',
			};
		},
		onLoad() {
			/* 检测版本更新
			调用util.js里面的 plus.runtime函数*/
			// #ifdef APP-PLUS
			plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
				this.version = widgetInfo.version;
			});
			// #endif
		},
		methods: {
		// 调用版本检测,util.js封装的 update检测版本方法
			update() {
		      // util.js方法中写了 showToas = true ,因为只有app需要检测版本更新
				this.$U.update(true);
			},
		},
	};
</script>

<style lang="scss"></style>

4. En la herramienta de configuración uniapp, configure el número de versión, publíquelo, empáquelo en el teléfono móvil y pruébelo usted mismo.

inserte la descripción de la imagen aquí

5. Escucha la red

// 监听网络状态
onNetWork() {
		let func = (res) => {
			console.log(res.networkType);
			// 如果处于 断网状态
			if (res.networkType === 'none' || res.isConnected === false) {
				uni.showToast({
					title: '当前处于断网状态,请先连接网络',
					icon: 'none',
					duration: 2000,
				});
			} else if (res.networkType !== 'none') {
				uni.showToast({
					title: '网络连接成功',
					icon: 'none',
					duration: 2000,
				});
			}
		}
		// 获取网络类型
		uni.getNetworkType({
			success: func
		});
		// 监听网络状态变化(只有网络发生改变时才触发)
		uni.onNetworkStatusChange(func);
	},

Por favor agregue una descripción de la imagen

borrar caché, función

<uni-list-item
			title="清除缓存"
			clickable
			showArrow
			@click="clear"
			:rightText="currentSize | format"

></uni-list-item>

Necesita un filtro, obtenga el caché del sistema y cargue directamente el código

export default {
		data() {
			return {
				// 缓存大小
				currentSize: 0,
			};
		},
		// 监听页面加载时
		onLoad() {
			// 调用 同步获取 系统缓存
			this.getStorageInfo();
		},
		// 过滤器
		filters: {
			// 将缓存 kb 转换为mb保留 两位小数
			format(value) {
				/* 如果 缓存大小>1024kb,就让它 除以1024kb.并保留两位小数,
				否则直接让value保留两位小数 */
				return value > 1024 ? (value / 1024).toFixed(2) + 'MB' : value.toFixed(2) + 'KB';
			},
		},
		methods: {
			// 同步获取系统 信息缓存
			getStorageInfo() {
				// 同步获取当前Storage的 详细信息
				let res = uni.getStorageInfoSync();
				this.currentSize = res.currentSize;
			},
			// 清除缓存
			clear() {
				if (this.currentSize == 0) {
					uni.showToast({
						title: '暂无缓存可清理',
						icon: 'none',
					});
					return;
				}
				uni.showModal({
					title: '提示',
					content: '是否要清除所有缓存?',
					cancelColor: '不清除',
					confirmColor: '清除',
					success: (res) => {
						if (res.confirm) {
							// 同步清理本地 数据缓存
							uni.clearStorageSync();
							// 清除完后,还需要再次调用,获取本地数据缓存
							this.getStorageInfo();
							uni.showToast({
								title: '清除成功',
								icon: 'none',
							});
						}
					},
				});
			},
		},
	};

Los pobres no pueden permitirse el lujo de comer, no solo lo mire, tomemos algo de RMB

Supongo que te gusta

Origin blog.csdn.net/weixin_46426412/article/details/130112330
Recomendado
Clasificación