After the vue project is updated, the file exists in the cache, and it needs to be refreshed to render the update

foreword

Every time a new version of the Vue project is released, testers must force a refresh to update the browser code to verify bugs. For users, this is even more unreasonable. So, find a way to let the browser automatically update the file.

start

1. Create a new version.json in the static static directory and change the version number in each release

{
    
    
    "version": "1.0.1"
}

2. Create a new libs/versionUpdate.js file in src

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
}

3. Write in the global route interception, as long as the version number is different each time, reload the page and cooperate with the first step to clear the browser cache

import versionTood from '@/libs/versionUpdate'
 
router.beforeEach(( to, from, next ) => {
    
    
  //判断当前代码版本是否与服务器中代码版本一致,如不一致则刷新页面获取最新
  versionTood.isNewVersion();

Guess you like

Origin blog.csdn.net/qq_39352780/article/details/118154096