vue 重新部署后刷新页面

思路 在打包时更新版号 判断版号不存在或者不相同时刷新下并且进行存储 在路由跳转时 对比存储的版号
1.首先设计一个版本号
2. 在路由守卫判断当前需不需要刷新 不同的刷新 相同的就不刷新

在public中放入js文件

console.log('build > 文件开始执行!')
const fs = require('fs')
const path = require('path')
function getRootPath(...dir) {
  return path.resolve(process.cwd(), ...dir)
}
const runBuild = async () => {
  try {
    const OUTPUT_DIR = 'public'
    const VERSION = 'version.json'
    const versionJson = {
      version: 'V_' + Math.floor(Math.random() * 10000) + Date.now()
    }
    fs.writeFileSync(getRootPath(`${OUTPUT_DIR}/${VERSION}`), JSON.stringify(versionJson))
    console.log(`version file is build successfully!`)
  } catch (error) {
    console.error('version build error:\n' + error)
    process.exit(1)
  }
}
runBuild()
console.log('build > 文件执行结束!')


在路由守卫 路由跳转的时候进行判断
在这里插入图片描述

 // 检查版本更新
   if (from.path !== '/') {
    checkAppNewVersion()
  }
async function checkAppNewVersion() {
  const url = `/version.json?t=${Date.now()}`
  let res = null
  try {
    res = await axios.get(url)
  } catch (err) {
    console.error('checkAppNewVersion error: ', err)
  }
  if (!res) return
  const version = res.data.version
  console.log(url);
    
  if (version && version !==  localStorage.getItem('version')) {
    localStorage.setItem('version', version)
    console.log('更新');
    // window.location.reload()
  }else{
    console.log('不更新');
  }
 
}





猜你喜欢

转载自blog.csdn.net/wzwzwz555/article/details/128866626