Vue检测获取最新资源 解决浏览器缓存问题
1、在public文件夹下创建version.json文件 2、vue.config.js中,每次打包动态更新version.json内容 3、App.vue中使用定时器去检测版本号和本地是否有差异
背景:由于浏览器缓存问题,vue2项目发布后,无法第一时间获取最新资源,影响使用
1、在public文件夹下创建version.json文件
2、vue.config.js中,每次打包动态更新version.json内容
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中使用定时器去检测版本号和本地是否有差异
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 )
}
}
} )
}