热更新原理
前端打包 app 即把写好的静态资源文件套壳打包成 app ,而热更新即下载并替换 app 内部的静态资源文件,实现 app 的版本升级。
在uni-app 中,我们是如何实现热更新的呢?下面来看代码
热更新实现
检查是否需要升级
// 检测升级
// #ifdef APP-PLUS
// var ver = plus.runtime.version;
var aid = plus.runtime.appid;
uni.request({
url: this.BaseUrl + '/api/update/version?version=' + this.localVersion + '&appid=' + aid + '&_t=' + new Date().getTime(),
method: 'GET',
success: result => {
var data = result.data;
if (data.update && data.wgtUrl) {
this.wgtUrl = data.wgtUrl;//保存下载地址
uni.showModal({
title: "发现新版本",
content: "确认下载更新",
success: (res) => {
if (res.confirm) {//当用户确定更新,执行更新
this.doUpData();
} else if (res.cancel) {
// console.log('用户点击取消');
}
}
})
}
},
complete: () => {
that.total += 1;
}
});
// #endif
确认需要升级
doUpData() {
uni.showLoading({
title: '更新中……'
})
uni.downloadFile({
url: this.wgtUrl,
success: downloadResult => {
if (downloadResult.statusCode === 200) {
uni.showModal({
title: '',
content: '更新成功,确定现在重启吗?',
confirmText: '重启',
confirmColor: '#EE8F57',
success: function(res) {
if (res.confirm) {
plus.runtime.install(
downloadResult.tempFilePath, {
force: true
},
function() {
// utils.showToast('更新成功,重启中');
plus.runtime.restart();
},
function(e) {
// utils.showToast('更新失败');
}
);
}
}
});
}
},
complete: () => {
uni.hideLoading();
}
});
}
注意
热更新查询的版本号是静态资源保存在本地的版本号,不是App本身的版本号。我是把本地版本存在了Vuex中,具体实现看个人需求。
可以在请求之前判断用户当前网络环境,提供更佳的用户体验。