第052个
专栏目标
在vue和element UI联合技术栈的操控下,本专栏提供行之有效的源代码示例和信息点介绍,做到灵活运用。
本文章目录
应用场景
在做vue项目时,每次打包发布新版到服务器上,相应的js,css等文件指纹都会发生变化。如何做热更新呢? 在笔者的项目中,localstorage中存储了很多用户相关的信息。新发布的时候,某些信息必须要做出改变。这个时候要求用户要重新登录,重新获取信息存储到localstorage中。
1. 配置发布版本,不统一强行退出重新登录
在软件开发过程中,为了方便管理和控制软件的版本,一般会根据软件的开发进度和发布计划,制定相应的版本号规则。常见的版本号格式包括以下几种:
- 主版本号(Major Version Number):表示软件的重大更新和改进,一般在软件功能发生重大变化或出现不兼容性时会升级,一般用数字表示。
- 次版本号(Minor Version Number):表示软件的次要更新和改进,一般在软件功能有一定改进或新增功能时会升级,一般用数字表示。
- 修订版本号(Patch Version Number):表示软件的修复和漏洞修正,一般在软件出现漏洞或错误时会发布更新版本,一般用数字表示。
- 编译版本号(Build Version Number):表示软件的编译版本和构建编号,一般用于区分不同的构建版本,一般用数字或字母表示。
(1)在main.js中配置版本号
(2)在主页面判断 新发布版本与localstorage中的版本号是否一致
getVersion(){
let v = localStorage.getItem("version");
if (v!= null) {
if(v!=this.$root.version){
this.$router.push({path: "/login"})
}
} else {
this.$router.push({path: "/login"})
}
},
在mounted生命周期中调用一下
(3)在login页面判断添加删除localStorage的version项
登录成功函数中添加这么一句
至此 版本不一致,就会重新登录,获取新的版本号信息。
2. 用户端一直挂机,页面不关掉,需要定时做判断,强迫重新登录
博主采用了https://blog.csdn.net/weixin_42000816/article/details/131800399 这篇文章的方案。
auto-update.js
let lastSrcs; //上一次获取到的script地址
let needTip = true; // 默认开启提示
const scriptReg = /<script.*src=["'](?<src>[^"']+)/gm;
async function extractNewScripts() {
const html = await fetch('/?_timestamp=' + Date.now()).then((resp) => resp.text());
scriptReg.lastIndex = 0;
let result = [];
let match;
while ((match = scriptReg.exec(html))) {
result.push(match.groups.src)
}
return result;
}
async function needUpdate() {
const newScripts = await extractNewScripts();
if (!lastSrcs) {
lastSrcs = newScripts;
return false;
}
let result = false;
if (lastSrcs.length !== newScripts.length) {
result = true;
}
for (let i = 0; i < lastSrcs.length; i++) {
if (lastSrcs[i] !== newScripts[i]) {
result = true;
break
}
}
lastSrcs = newScripts;
return result;
}
const DURATION = 5000;
function autoRefresh() {
setTimeout(async () => {
const willUpdate = await needUpdate();
if (willUpdate) {
const result = confirm("页面有更新,请刷新查看");
if (result) {
location.href('/login');
}
needTip = false;
}
if(needTip){
autoRefresh();
}
}, DURATION)
}
autoRefresh();
注意 :跟原作者的判断稍有不同,就是非自动刷新页面,而是跳转到登录的页面。
在main.js中引入
后端处理方案
后来后端的同事,出了一个更简单实用的方案,在nginx 上设置协商缓存与强缓存,不用前端来处理了。
location /test {
#try_files $uri $uri/ /notFound.html;
#index index.html index.htm;
if ($request_uri ~* .*[.](js|css|map|jpg|png|svg|ico)$) {
add_header Cache-Control "public, max-age=25920000";#非html缓存1个月
}
if ($request_filename ~* ^.*[.](html|htm)$) {
add_header Cache-Control "public, no-cache";
}
}
详情参考:https://article.juejin.cn/post/7215881683294879801