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
| import { ref, onMounted, onUnmounted } from "vue" export function useVersionCheck(options = {}) { const { interval = 60000, 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, } }
|