优化组件加载逻辑

This commit is contained in:
jxxghp
2025-06-30 20:38:50 +08:00
parent 30d933bd85
commit b01421aa94
5 changed files with 105 additions and 59 deletions
+64 -45
View File
@@ -41,26 +41,33 @@ declare global {
} }
} }
if (window.Apex) { // 配置 ApexCharts 全局选项
// 数据标签 function configureApexCharts() {
window.Apex.dataLabels = { if (typeof window !== 'undefined' && window.Apex) {
formatter: function (_: number, { seriesIndex, w }: { seriesIndex: number; w: any }) { try {
// 如果有小数点,保留两位小数,否则保留整 // 数据标签
const data = w.config.series[seriesIndex] window.Apex.dataLabels = {
return data.toFixed(data % 1 === 0 ? 0 : 1) formatter: function (_: number, { seriesIndex, w }: { seriesIndex: number; w: any }) {
}, // 如果有小数点,保留两位小数,否则保留整数
} const data = w.config.series[seriesIndex]
// 图例 return data.toFixed(data % 1 === 0 ? 0 : 1)
window.Apex.legend = { },
labels: { }
useSeriesColors: true, // 图例
}, window.Apex.legend = {
} labels: {
// 标题 useSeriesColors: true,
window.Apex.title = { },
style: { }
color: 'rgba(var(--v-theme-on-surface), var(--v-high-emphasis-opacity))', // 标题
}, window.Apex.title = {
style: {
color: 'rgba(var(--v-theme-on-surface), var(--v-high-emphasis-opacity))',
},
}
} catch (error) {
console.warn('ApexCharts 全局配置失败:', error)
}
} }
} }
@@ -74,10 +81,13 @@ function updateHtmlThemeAttribute(themeName: string) {
// 获取背景图片 // 获取背景图片
async function fetchBackgroundImages() { async function fetchBackgroundImages() {
try { try {
backgroundImages.value = await api.get(`/login/wallpapers`) const controller = new AbortController()
backgroundImages.value = await api.get(`/login/wallpapers`, {
signal: controller.signal,
})
activeImageIndex.value = 0 activeImageIndex.value = 0
} catch (e) { } catch (e) {
console.error(e) throw e
} }
} }
@@ -85,7 +95,6 @@ async function fetchBackgroundImages() {
function startBackgroundRotation() { function startBackgroundRotation() {
// 清除轮换定时器 // 清除轮换定时器
if (backgroundRotationTimer) clearInterval(backgroundRotationTimer) if (backgroundRotationTimer) clearInterval(backgroundRotationTimer)
if (backgroundImages.value.length > 1) { if (backgroundImages.value.length > 1) {
backgroundRotationTimer = setInterval(() => { backgroundRotationTimer = setInterval(() => {
// 计算下一个图片索引 // 计算下一个图片索引
@@ -131,7 +140,6 @@ function animateAndRemoveLoader() {
if (loadingBg) { if (loadingBg) {
// 先添加完成动画类 // 先添加完成动画类
loadingBg.classList.add('loading-complete') loadingBg.classList.add('loading-complete')
// 等待动画完成后再移除元素 // 等待动画完成后再移除元素
setTimeout(() => { setTimeout(() => {
removeEl('#loading-bg') removeEl('#loading-bg')
@@ -144,20 +152,27 @@ function animateAndRemoveLoader() {
} }
// 加载背景图片 // 加载背景图片
async function loadBackgroundImages() { async function loadBackgroundImages(retryCount = 0) {
await fetchBackgroundImages() const maxRetries = 3
.then(() => { try {
startBackgroundRotation() await fetchBackgroundImages()
}) startBackgroundRotation()
.catch(() => { } catch (error: any) {
// 3秒后重试 const isAbortError = error.name === 'AbortError' || error.code === 'ERR_CANCELED'
if (retryCount < maxRetries) {
const baseDelay = isAbortError ? 1000 : 3000
const retryDelay = Math.min(baseDelay * Math.pow(2, retryCount), 10000)
setTimeout(() => { setTimeout(() => {
loadBackgroundImages() loadBackgroundImages(retryCount + 1)
}, 3000) }, retryDelay)
}) }
}
} }
onMounted(async () => { onMounted(async () => {
// 配置 ApexCharts
configureApexCharts()
// 初始化data-theme属性 // 初始化data-theme属性
updateHtmlThemeAttribute(globalTheme.name.value) updateHtmlThemeAttribute(globalTheme.name.value)
@@ -165,7 +180,7 @@ onMounted(async () => {
show.value = false show.value = false
// 加载背景图片 // 加载背景图片
await loadBackgroundImages() loadBackgroundImages()
// 移除加载动画 // 移除加载动画
ensureRenderComplete(() => { ensureRenderComplete(() => {
@@ -173,7 +188,6 @@ onMounted(async () => {
setTimeout(() => { setTimeout(() => {
// 移除加载动画,显示页面 // 移除加载动画,显示页面
animateAndRemoveLoader() animateAndRemoveLoader()
// 页面完全显示后,检查未读消息 // 页面完全显示后,检查未读消息
setTimeout(() => { setTimeout(() => {
checkAndEmitUnreadMessages() checkAndEmitUnreadMessages()
@@ -185,11 +199,14 @@ onMounted(async () => {
// 添加页面可见性变化监听 // 添加页面可见性变化监听
document.addEventListener('visibilitychange', () => { document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') { if (document.visibilityState === 'visible') {
loadBackgroundImages() // 页面恢复可见时,稍作延迟以确保状态稳定
// 页面恢复可见时检查未读消息
setTimeout(() => { setTimeout(() => {
checkAndEmitUnreadMessages() loadBackgroundImages()
}, 500) // 检查未读消息
setTimeout(() => {
checkAndEmitUnreadMessages()
}, 300)
}, 100)
} }
}) })
@@ -197,11 +214,14 @@ onMounted(async () => {
window.addEventListener('pageshow', event => { window.addEventListener('pageshow', event => {
// persisted属性为true表示页面是从bfcache中恢复的 // persisted属性为true表示页面是从bfcache中恢复的
if (event.persisted) { if (event.persisted) {
loadBackgroundImages() // PWA恢复时,稍作延迟以确保状态稳定
// PWA恢复时检查未读消息
setTimeout(() => { setTimeout(() => {
checkAndEmitUnreadMessages() loadBackgroundImages()
}, 500) // 检查未读消息
setTimeout(() => {
checkAndEmitUnreadMessages()
}, 300)
}, 100)
} }
}) })
}) })
@@ -211,7 +231,6 @@ onUnmounted(() => {
document.removeEventListener('visibilitychange', () => {}) document.removeEventListener('visibilitychange', () => {})
// 移除PWA的页面恢复事件监听 // 移除PWA的页面恢复事件监听
window.removeEventListener('pageshow', () => {}) window.removeEventListener('pageshow', () => {})
// 清除轮换定时器 // 清除轮换定时器
if (backgroundRotationTimer) { if (backgroundRotationTimer) {
clearInterval(backgroundRotationTimer) clearInterval(backgroundRotationTimer)
+7 -2
View File
@@ -253,6 +253,8 @@ async function fetchSiteUserData() {
try { try {
const result: { [key: string]: any } = await api.get(`site/userdata/${props.site?.id}`) const result: { [key: string]: any } = await api.get(`site/userdata/${props.site?.id}`)
if (result.success) { if (result.success) {
// 使用nextTick确保DOM更新完成后再更新图表数据
await nextTick()
siteDatas.value = result.data.sort((a: { updated_day: any }, b: { updated_day: any }) => siteDatas.value = result.data.sort((a: { updated_day: any }, b: { updated_day: any }) =>
(a.updated_day || '').localeCompare(b.updated_day || ''), (a.updated_day || '').localeCompare(b.updated_day || ''),
) )
@@ -276,8 +278,11 @@ async function refreshSiteData() {
progressDialog.value = false progressDialog.value = false
} }
onBeforeMount(async () => { onBeforeMount(() => {
await fetchSiteUserData() // 延迟加载,确保组件完全挂载
nextTick(() => {
fetchSiteUserData()
})
}) })
</script> </script>
+11 -4
View File
@@ -112,6 +112,8 @@ async function getCpuUsage() {
try { try {
// 请求数据 // 请求数据
current.value = (await api.get('dashboard/cpu')) ?? 0 current.value = (await api.get('dashboard/cpu')) ?? 0
// 使用nextTick确保DOM更新完成后再更新图表数据
await nextTick()
// 添加到序列 // 添加到序列
series.value[0].data.push(current.value) series.value[0].data.push(current.value)
// 序列超过30条记录时,清掉前面的 // 序列超过30条记录时,清掉前面的
@@ -122,10 +124,13 @@ async function getCpuUsage() {
} }
onMounted(() => { onMounted(() => {
getCpuUsage() // 启动定时器 // 延迟启动,确保组件完全挂载
refreshTimer = setInterval(() => { nextTick(() => {
getCpuUsage() getCpuUsage()
}, 2000) refreshTimer = setInterval(() => {
getCpuUsage()
}, 2000)
})
}) })
// 组件卸载时停止定时器 // 组件卸载时停止定时器
@@ -137,7 +142,9 @@ onUnmounted(() => {
}) })
onActivated(() => { onActivated(() => {
chartKey.value += 1 nextTick(() => {
chartKey.value += 1
})
}) })
</script> </script>
+13 -5
View File
@@ -118,6 +118,8 @@ async function getMemorgUsage() {
try { try {
// 请求数据 // 请求数据
;[usedMemory.value, memoryUsage.value] = await api.get('dashboard/memory') ;[usedMemory.value, memoryUsage.value] = await api.get('dashboard/memory')
// 使用nextTick确保DOM更新完成后再更新图表数据
await nextTick()
series.value[0].data.push(memoryUsage.value) series.value[0].data.push(memoryUsage.value)
// 序列超过30条记录时,清掉前面的 // 序列超过30条记录时,清掉前面的
if (series.value[0].data.length > 30) series.value[0].data.shift() if (series.value[0].data.length > 30) series.value[0].data.shift()
@@ -127,11 +129,14 @@ async function getMemorgUsage() {
} }
onMounted(() => { onMounted(() => {
getMemorgUsage() // 延迟启动,确保组件完全挂载
// 启动定时器 nextTick(() => {
refreshTimer = setInterval(() => {
getMemorgUsage() getMemorgUsage()
}, 3000) // 启动定时器
refreshTimer = setInterval(() => {
getMemorgUsage()
}, 3000)
})
}) })
// 组件卸载时停止定时器 // 组件卸载时停止定时器
@@ -143,7 +148,10 @@ onUnmounted(() => {
}) })
onActivated(() => { onActivated(() => {
chartKey.value += 1 // 使用nextTick确保DOM准备完成后再更新chartKey
nextTick(() => {
chartKey.value += 1
})
}) })
</script> </script>
@@ -107,7 +107,8 @@ const totalCount = computed(() => series.value[0].data.reduce((a, b) => a + b, 0
async function getWeeklyData() { async function getWeeklyData() {
try { try {
const res: number[] = await api.get('dashboard/transfer') const res: number[] = await api.get('dashboard/transfer')
// 使用nextTick确保DOM更新完成后再更新图表数据
await nextTick()
series.value = [{ data: res }] series.value = [{ data: res }]
} catch (e) { } catch (e) {
console.log(e) console.log(e)
@@ -115,11 +116,17 @@ async function getWeeklyData() {
} }
onMounted(() => { onMounted(() => {
getWeeklyData() // 延迟启动,确保组件完全挂载
nextTick(() => {
getWeeklyData()
})
}) })
onActivated(() => { onActivated(() => {
getWeeklyData() // 使用nextTick确保DOM准备完成后再获取数据
nextTick(() => {
getWeeklyData()
})
}) })
</script> </script>