当在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