vue 前端实现版本检测

2023-06-16  本文已影响0人  贺大大i

思路:
每次打包会产生新的hash值,那么能不能通过获取当前页面的hash和最新的hash进行比较,如果hash相同就说明当前版本就是最新版本。

此时有个问题就是如何获取最新的hash?

通过ajax请求肯定是会得到最新的数据,那么如果我在路由切换时请求当前页面,那么肯定能够拿到返回的数据,动态创建html,通过html获取script中的hash就能拿到最新的hash···

我是2分钟和路由切换调用,自己根据情况选择调用。亲测有用

参考文章:http://www.guanshanw.com/post/23670.html
我按照上面的配置会报错。
vite 前端检测版本更新,后续更新

import axios from 'axios';

 
 data() {
    return {
      cur_hash: false,
      iMessage: false,
      verUpdate: false
    };
  },
  watch: {
    $route(to, from) {
      this.getHash();
    }
  },
  methods: {
    async getHash() {
      axios
        .get(
          `${window.location.origin}${
            window.location.pathname
          }index.html?time=${new Date().getTime()}`,
          {
            withCredentials: true,
            mode: 'no-cors',
            headers: {
              'Access-Control-Allow-Origin': '*',
              'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS'
            }
          }
        )
        .then(async (res) => {
          // 返回的是字符串,需要转换为 html
          let el = document.createElement('html');
          el.innerHTML = res.data;

          let spt = el.getElementsByTagName('script');

          // 拿到 hash
          let new_hash = '';
          for (let i = 0; i < spt.length; i++) {
            const element = spt[i];
            if (spt[i].src.indexOf('checkhash') !== -1) {
              new_hash = spt[i].src.split('.')[spt[i].src.split('.').length - 1];
              break;
            }
          }

          if (!this.cur_hash) {
            this.cur_hash = new_hash;
            return;
          }

          // iMessage 是个全局变量(默认值 false),用来帮助判断什么时候会弹出提示,不然定时器就一直弹
          if (new_hash != this.cur_hash && !this.iMessage) {
            // 版本更新,弹出提示
            this.iMessage = true;

            const h = this.$createElement;
            this.$message.success({
              message: h('span', null, [
                h('span', null, '当前版本已更新,请刷新后使用 '),
                h(
                  'a',
                  {
                    on: {
                      click: function () {
                        window.location.reload();
                      }
                    },
                    style:
                      'cursor:pointer;color:rgb(22, 96, 199);padding: 2px 0'
                  },
                  '刷新页面'
                )
              ]),

              duration: 0,
              showClose: true,
              customClass: 'refresh'
            });
          }
        });
    }
  },
  mounted() {
    setInterval(() => {
      this.getHash();
    }, 120000);
  }

vue.config.js

const Version = new Date().getTime();

chainWebpack 下

config.output.filename(`js/checkhash[name].[checkhash].${Version}.js?t=${Version}`).end();
config.output.chunkFilename(`js/[id].[checkhash].${Version}.js?t=${Version}`).end();
上一篇 下一篇

猜你喜欢

热点阅读