Vue项目客户端自动监测更新解决方案

 当在Vue项目中创建客户端自动监测更新的解决方案时,你可以使用以下代码示例。这段代码将周期性地检查页面上的<script>标签是否有新版本,并在检测到新版本时弹出更新提示框。

import { MessageBox } from 'element-ui'


let lastSrcs; //上一次获取到的script地址
let needTip = true; // 默认开启提示

const scriptReg = /<script\s+src=([^>\s]+)(?:\s|>)<\/script>/gm;

async function extractNewScripts() {
  const html = await fetch('/?_timestamp=' + Date.now()).then((resp) => resp.text());
  scriptReg.lastIndex = 0;
  let result = [];
  let match;
  while ((match = scriptReg.exec(html))) {
    result.push(match[1])
  }
  return result;
}

async function needUpdate() {
  const newScripts = await extractNewScripts();
  if (!lastSrcs) {
    lastSrcs = newScripts;
    return false;
  }
  let result = false;
  if (lastSrcs.length !== newScripts.length) {
    result = true;
  }
  for (let i = 0; i < lastSrcs.length; i++) {
    if (lastSrcs[i] !== newScripts[i]) {
      result = true;
      break
    }
  }
  lastSrcs = newScripts;
  return result;
}
const DURATION = 5000;

function autoRefresh() {
  setTimeout(async () => {
    const willUpdate = await needUpdate();
    if (willUpdate) {
      MessageBox.confirm('有新版本啦,快更新ヾ(≧▽≦*)o!!!', '系统提示', {
          confirmButtonText: '立即更新',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        window.location.reload();
      });
      needTip = false; // 关闭更新提示,防止重复提醒
    }
    if(needTip){
      autoRefresh();
    }
  }, DURATION)
}
autoRefresh();

在这段代码中,我们首先定义了extractNewScripts函数,它会获取页面中的所有<script>标签的src属性。接下来,needUpdate函数会比较新获取的<script>标签数组和上一次获取的数组,以判断是否需要更新。

最后,autoRefresh函数会周期性地调用needUpdate函数,如果需要更新,它会弹出一个提示框,提示用户有新版本可用。用户可以选择立即更新或取消。此外,needTip变量用于控制是否需要提示用户,以防止重复提醒。

你可以将这段代码添加到你的Vue项目中,以实现客户端自动监测更新的功能。

main.js

import '@/utils/autoUpdate' // auto Update Version

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值