自动刷新更新

1. 创建脚本,生成version.json 保存新版本号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import fs from "fs"
import path from "path"
import { fileURLToPath } from "url"

const __filename = fileURLToPath(import.meta.url)

const __dirname = path.dirname(__filename)

// 生成版本信息:时间戳 + 格式化日期时间

const version = {
version: Date.now().toString(),
buildTime: new Date().toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" }),
commitHash: process.env.commitHash || "unknown",
}

// 写入到public 目录

const publicDir = path.resolve(__dirname, "../public")
if (!fs.existsSync(publicDir)) {
fs.mkdirSync(publicDir, { recursive: true })
}

fs.writeFileSync(path.resolve(publicDir, "version.json"), JSON.stringify(version, null, 2))

console.log(`版本已生成 ${version.buildTime} ${version.version}`)
1
2
3
4
5
"scripts": {
"dev": "vite ",
"build": "node scripts/generate-version.js && vite build ",
"preview": "vite preview"
},

2.轮询判断版本号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// composables/useVersionCheck.js
import { ref, onMounted, onUnmounted } from "vue"
export function useVersionCheck(options = {}) {
const {
interval = 60000, // 轮询间隔,默认60秒
immediate = true, // 是否立即开始检测
showNotification = true, // 是否显示通知
autoReloadDelay = 3000, // 自动刷新延迟(毫秒)
} = options

const currentVersion = ref(null)
const isChecking = ref(false)
const isRefreshing = ref(false)
const hasUpdate = ref(false)
let timer = null

// 获取最新版本信息
const fetchVersion = async () => {
try {
// 添加时间戳防止缓存
const url = `/version.json?t=${Date.now()}`

const response = await fetch(url, {
cache: "no-cache",
headers: {
"Cache-Control": "no-cache",
Pragma: "no-cache",
},
})

if (!response.ok) {
throw new Error(`HTTP ${response.status}`)
}

const data = await response.json()

return data.version
} catch (error) {
console.warn("[版本检测] 获取版本失败:", error)
return null
}
}

// 轮询检查
const startChecking = () => {
if (timer) return

timer = setInterval(() => {
if (document.visibilityState === "visible") {
checkVersion()
}
}, 10000)
}

// 检查版本更新
const checkVersion = async () => {
console.log("轮询")

if (isChecking.value || isRefreshing.value) return

isChecking.value = true

try {
const newVersion = await fetchVersion()

if (!newVersion) return

//首次获取版本
if (!currentVersion.value) {
currentVersion.value = newVersion

console.log("版本检测", currentVersion.value)

return
}

// 版本对比

if (currentVersion.value !== newVersion && !hasUpdate.value) {
console.log("版本检测", {
old: currentVersion.value,
new: newVersion,
})

hasUpdate.value = true

currentVersion.value = newVersion

// 自动刷新
console.log("我要开始刷新")
setTimeout(() => {
window.location.reload()
}, 3000)
}
} catch (error) {
console.error("版本检测失败", error)
} finally {
isChecking.value = false
}
}

// 监听页面可见性变化
const handleVisibilityChange = () => {
if (document.visibilityState === "visible" && timer && !hasUpdate.value) {
// 页面重新可见时立即检测一次

checkVersion()
}
}

onMounted(() => {
document.addEventListener("visibilitychange", handleVisibilityChange)
})

onUnmounted(() => {
document.removeEventListener("visibilitychange", handleVisibilityChange)
clearInterval(timer)
})

return {
startChecking,
}
}

3.使用

1
2
3
4
5
import { useVersionCheck } from "./composables/useVersionCheck"

const { startChecking } = useVersionCheck()

startChecking()

本文作者:finyou

本文链接:http://finyou.top/2026/04/22/Vue/autoRefresh/

版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!

ESC 关闭 | 导航 | Enter 打开
输入关键词开始搜索