Vue3+Vite 自动检测线上环境 版本热更新

       当用户停留在当前页面很久,此时页面升级更新。若用户不刷新,就会一直停留在当前旧版本的页面上。现给予用户升级版本的提醒:

在utils文件夹下新建autoUpdate.ts 

import { ElMessageBox } from 'element-plus';

let lastScripts: string[] = [];
const DURATION = 60 * 1000; //设置每分钟更新一次

//提取html中的script标签的src属性
async function extractNewScripts(html: string): Promise<string[]> {
	const scriptReg = /<script.*src=["'](?<src>[^"']+)/gm; //匹配script标签并捕获src属性内的URL
	const result: string[] = [];
	let match;
	while ((match = scriptReg.exec(html))) {
		result.push(match.groups?.src ?? '');
	}
	return result;
}

//判断是否需要更新
async function needUpdate(): Promise<boolean> {
	//获取当前页面的script标签src属性
	const newScripts = await extractNewScripts(await fetch('/').then((resp) => resp.text()));
	//如果是第一次加载,则不更新
	if (!lastScripts.length) {
		lastScripts = newScripts;
		return false;
	}
	//判断是否需要更新 长度不同-更新
	if (newScripts.length !== lastScripts.length) {
		lastScripts = newScripts;
		return true;
	}
	//比较两个数组是否相等 长度相同,内容不同-更新
	for (let i = 0; i < lastScripts.length; i++) {
		if (lastScripts[i] !== newScripts[i]) {
			lastScripts = newScripts;
			return true;
		}
	}
	return false;
}

/* 自动刷新 */
export const autoRefresh = (): void => {
	setTimeout(async () => {
		const willUpdate = await needUpdate();
		if (willUpdate) {
			ElMessageBox.confirm('页面有更新,点击确定刷新页面?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					location.reload();
				})
				.catch(() => { });
		}
		else {
			autoRefresh();// 如果不需要更新数据,继续执行下一次判断
		}
	}, DURATION);
};

在首页home.vue中使用

import { autoRefresh } from '/@/utils/autoUpdate';
onMounted(() => {
	nextTick(() => {
		if (import.meta.env.MODE !== 'development') autoRefresh();
	});
});

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值