一、vue2
1.配置webpack.prod.conf.js
//设置output加t=[chunkhash:8]相当于加时间戳,用于清缓存 output: { path: config.build.assetsRoot, filename: utils.assetsPath('js/[name].[chunkhash].js?t=[chunkhash:8]'), chunkFilename: utils.assetsPath('js/[id].[chunkhash].js?t=[chunkhash:8]') },
2.在static静态目录下新建version.json每次发版更改里面的版本号
{ "version": "0.0.1" }
3.在src中新建 libs/versionUpdate.js文件
import axios from 'axios' const isNewVersion = () => { let url = `//${window.location.host}/static/version.json?t=${new Date().getTime()}`; axios.get(url).then(res => { if (res.status === 200) { let vueVersion = res.data.version; let localVueVersion = localStorage.getItem('vueVersion'); if (localVueVersion && localVueVersion != vueVersion) { localStorage.setItem('vueVersion', vueVersion); window.location.reload(); return; } else { localStorage.setItem('vueVersion', vueVersion); } } }); } export default { isNewVersion }
4.全局路由拦截中写,只要每次版本号不同就重新加载页面配合第一步就可以清楚浏览器缓存
import versionTood from '@/libs/versionUpdate' router.beforeEach(( to, from, next ) => { //判断当前代码版本是否与服务器中代码版本一致,如不一致则刷新页面获取最新 versionTood.isNewVersion();
二、vue3
1.在vue.config.js中配置output
const Timestamp = new Date().getTime(); configureWebpack: { output: { filename: `js/[name].${Timestamp}.js`, // 每次构建打包时给文件名加上时间戳,确保每次版本更新的文件名不一样 chunkFilename: `js/[name].${Timestamp}.js` } }
2.在public目录下新建version.json每次发版更改里面的版本号
{ "version": "0.0.1" }
3.在src中新建 libs/versionUpdate.js文件
import axios from 'axios' const isNewVersion = () => { let url = `//${window.location.host}/static/version.json?t=${new Date().getTime()}`; axios.get(url).then(res => { if (res.status === 200) { let vueVersion = res.data.version; let localVueVersion = localStorage.getItem('vueVersion'); if (localVueVersion && localVueVersion != vueVersion) { localStorage.setItem('vueVersion', vueVersion); window.location.reload(); return; } else { localStorage.setItem('vueVersion', vueVersion); } } }); } export default { isNewVersion }
4.全局路由拦截中写,只要每次版本号不同就重新加载页面配合第一步就可以清楚浏览器缓存
import versionTood from '@/libs/versionUpdate' router.beforeEach(( to, from, next ) => { //判断当前代码版本是否与服务器中代码版本一致,如不一致则刷新页面获取最新 versionTood.isNewVersion();