perf: 优化路由守卫安装检查,使用 localStorage 缓存
- 将安装状态缓存到 localStorage,有效期 24 小时 - 避免每次路由切换都发起 HTTP 请求 - 显著提升页面切换速度
This commit is contained in:
@@ -1,25 +1,52 @@
|
|||||||
import type { Router } from 'vue-router'
|
import type { Router } from 'vue-router'
|
||||||
|
|
||||||
let installChecked = false
|
const INSTALL_CACHE_KEY = 'app_installed'
|
||||||
let isInstalled = false
|
const INSTALL_CACHE_EXPIRY = 24 * 60 * 60 * 1000
|
||||||
|
|
||||||
|
function getCachedInstallStatus(): boolean | null {
|
||||||
|
try {
|
||||||
|
const cached = localStorage.getItem(INSTALL_CACHE_KEY)
|
||||||
|
if (cached) {
|
||||||
|
const { installed, timestamp } = JSON.parse(cached)
|
||||||
|
if (Date.now() - timestamp < INSTALL_CACHE_EXPIRY) {
|
||||||
|
return installed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function setCachedInstallStatus(installed: boolean) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(INSTALL_CACHE_KEY, JSON.stringify({
|
||||||
|
installed,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function resetInstallCheck() {
|
export function resetInstallCheck() {
|
||||||
installChecked = false
|
localStorage.removeItem(INSTALL_CACHE_KEY)
|
||||||
isInstalled = false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function checkInstallStatus(): Promise<boolean> {
|
async function checkInstallStatus(): Promise<boolean> {
|
||||||
if (installChecked) return isInstalled
|
const cached = getCachedInstallStatus()
|
||||||
|
if (cached !== null) return cached
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/install/status')
|
const res = await fetch('/api/install/status')
|
||||||
const data = await res.json()
|
const data = await res.json()
|
||||||
isInstalled = data?.data?.installed ?? false
|
const installed = data?.data?.installed ?? false
|
||||||
installChecked = true
|
setCachedInstallStatus(installed)
|
||||||
return isInstalled
|
return installed
|
||||||
}
|
}
|
||||||
catch {
|
catch {
|
||||||
installChecked = true
|
setCachedInstallStatus(false)
|
||||||
isInstalled = false
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user