Vue检测获取最新资源 解决浏览器缓存问题

Vue检测获取最新资源 解决浏览器缓存问题

1、在public文件夹下创建version.json文件

2、vue.config.js中,每次打包动态更新version.json内容

javascript 复制代码
let fs = require('fs');
const version = new Date().getTime();
let vJSON = require('./public/version.json') || {}
if ( process.env.NODE_ENV === "production" ) {
  vJSON = { 'version': version + '' }
  fs.writeFile('./public/version.json', JSON.stringify(vJSON), () => {
    console.log('新版本号生成成功');
  });
}

3、App.vue中使用定时器去检测版本号和本地是否有差异

javascript 复制代码
timer: null // 定时器实例

this.getLatestResources(true)
// 每半小时监测一次是否有更新
this.timer = setInterval(() => {
  this.getLatestResources()
}, 30 * 60 * 1000)

// 获取最新资源
getLatestResources(b = false) {
  this.$axios.get("/xxxxxxx/version.json",{params:{data: new Date().getTime()}}).then(res => {
    let lastVersion = res.data.version
    let storageVersion = localStorage.getItem("version")
    if (!storageVersion) {
      localStorage.setItem("version", lastVersion)
    } else {
      if(storageVersion != lastVersion){
        localStorage.removeItem("version")
        this.timer && clearInterval(this.timer)
        !b && this.$Modal.info({
          title: "提示",
          content: '检测到系统有更新,请刷新浏览器后使用!',
          onOk: () => {
            this.$router.go(0)
          }
        });
        b && this.$router.go(0)
      }
    }
  })
}
相关推荐
li35741 天前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron
Icoolkj1 天前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js
MAGICIAN...1 天前
【Redis】--持久化机制
数据库·redis·缓存
我真的是大笨蛋1 天前
JVM调优总结
java·jvm·数据库·redis·缓存·性能优化·系统架构
^Rocky1 天前
JavaScript性能优化实战
开发语言·javascript·性能优化
西陵1 天前
Nx带来极致的前端开发体验——任务编排
前端·javascript·架构
笑鸿的学习笔记1 天前
JavaScript笔记之JS 和 HTML5 的关系
javascript·笔记·html5
萌萌哒草头将军1 天前
10个 ES2025 新特性速览!🚀🚀🚀
前端·javascript·vue.js
gnip1 天前
http缓存
前端·javascript
JohnYan1 天前
工作笔记 - 微信消息发送和处理
javascript·后端·微信