Vue 前端版本更新提示,通知用户刷新UI
前端更新程序后,通知用户刷新UI
需要手动修改版本号
- 在 public 目录下 创建 version.json
{
"version": "1.0.0"
}
src\App.vue文件中添加如下代码
<script setup lang="ts">
// 检查版本更新
const checkVersion = async () => {
try {
// 添加时间戳防止缓存
const response = await fetch("/version.json?t=" + new Date().getTime());
const data = await response.json();
const localVersion = localStorage.getItem("app_version");
if (localVersion && localVersion !== data.version) {
showUpdateNotification();
}
localStorage.setItem("app_version", data.version);
} catch (error) {
console.error("检查版本更新失败:", error);
}
};
// 显示更新通知
const showUpdateNotification = () => {
ElNotification({
title: "系统更新提示",
message: "系统已更新,请刷新页面获取最新版本",
type: "warning",
duration: 0,
onClick: () => window.location.reload(),
onClose: () => window.location.reload(),
});
};
// 组件挂载时初始化
onMounted(() => {
localStorage.removeItem("app_version"); // 清除本地版本号
checkVersion(); // 初始检查
setInterval(checkVersion, 60000); // 每分钟检查一次
});
</script>
根据格式,获取当前时间
/**
* 根据格式,获取当前时间
* @param dateFormat 默认:yyyy-MM-dd HH:mm:ss
*/
export function getCurrentTime(dateFormat = "yyyy-MM-dd HH:mm:ss"): string {
const date = new Date();
let year = String(date.getFullYear());
if (dateFormat == "yyMMddHHmmss") {
year = year.slice(-2); // 取年份的后两位
}
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
const seconds = String(date.getSeconds()).padStart(2, "0");
let result = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
if (dateFormat == "yyMMddHHmmss") {
result = `${year}${month}${day}${hours}${minutes}${seconds}`;
}
return result;
}
自动构建
构建的时候,生成json文件内容,其实还是基于json或者环境去配置。还是要手改,记录一下防止以后别的地方用得到
src\plugins\ 下创建 version-update.ts
import { writeFileSync, readFileSync } from "fs";
import { resolve } from "path";
export default function versionUpdatePlugin(options = {}) {
return {
name: "version-update-plugin",
apply: "build",
closeBundle() {
try {
const rootDir = process.cwd();
const packageJsonPath = resolve(rootDir, "package.json");
const versionJsonPath = resolve(rootDir, "public/version.json"); // 你的 JSON 文件路径
// 读取 package.json 的版本号
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
//const packageVersion = packageJson.version; //可删除,不需要太正式
const packageVersion = Date.now().toString(); //只是为了做升级提醒,不用查看具体版本号,所以不需要太正式
// 读取或创建版本 JSON 文件
let versionData = {};
try {
versionData = JSON.parse(readFileSync(versionJsonPath, "utf8"));
} catch (error) {
// 文件不存在,创建新文件
versionData = { version: packageVersion };
}
// 更新版本号
versionData.version = packageVersion;
// 写入文件
writeFileSync(versionJsonPath, JSON.stringify(versionData, null, 2));
console.log(`✅ Version updated to ${packageVersion} in version.json`);
} catch (error) {
console.error("❌ Failed to update version:", error);
}
},
};
}
vite.config.ts
import versionUpdatePlugin from "./src/plugins/version-update";
export default defineConfig(({ mode }: ConfigEnv) => {
const env = loadEnv(mode, process.cwd());
return {
plugins: [
vue(),
versionUpdatePlugin("1.0.1"),
env.VITE_MOCK_DEV_SERVER === "true" ? mockDevServerPlugin() : null,
]
}
}
本文来自博客园,作者:VipSoft 转载请注明原文链接:https://www.cnblogs.com/vipsoft/p/19067664
浙公网安备 33010602011771号