优化组件加载逻辑

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
+39 -20
View File
@@ -41,7 +41,10 @@ declare global {
} }
} }
if (window.Apex) { // 配置 ApexCharts 全局选项
function configureApexCharts() {
if (typeof window !== 'undefined' && window.Apex) {
try {
// 数据标签 // 数据标签
window.Apex.dataLabels = { window.Apex.dataLabels = {
formatter: function (_: number, { seriesIndex, w }: { seriesIndex: number; w: any }) { formatter: function (_: number, { seriesIndex, w }: { seriesIndex: number; w: any }) {
@@ -62,6 +65,10 @@ if (window.Apex) {
color: 'rgba(var(--v-theme-on-surface), var(--v-high-emphasis-opacity))', color: 'rgba(var(--v-theme-on-surface), var(--v-high-emphasis-opacity))',
}, },
} }
} catch (error) {
console.warn('ApexCharts 全局配置失败:', error)
}
}
} }
// 更新data-theme属性以便CSS选择器能正确匹配 // 更新data-theme属性以便CSS选择器能正确匹配
@@ -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) {
const maxRetries = 3
try {
await fetchBackgroundImages() await fetchBackgroundImages()
.then(() => {
startBackgroundRotation() startBackgroundRotation()
}) } catch (error: any) {
.catch(() => { const isAbortError = error.name === 'AbortError' || error.code === 'ERR_CANCELED'
// 3秒后重试 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') {
// 页面恢复可见时,稍作延迟以确保状态稳定
setTimeout(() => {
loadBackgroundImages() loadBackgroundImages()
// 页面恢复可见时检查未读消息 // 检查未读消息
setTimeout(() => { setTimeout(() => {
checkAndEmitUnreadMessages() checkAndEmitUnreadMessages()
}, 500) }, 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) {
// PWA恢复时,稍作延迟以确保状态稳定
setTimeout(() => {
loadBackgroundImages() loadBackgroundImages()
// PWA恢复时检查未读消息 // 检查未读消息
setTimeout(() => { setTimeout(() => {
checkAndEmitUnreadMessages() checkAndEmitUnreadMessages()
}, 500) }, 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>
+8 -1
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() // 启动定时器 // 延迟启动,确保组件完全挂载
nextTick(() => {
getCpuUsage()
refreshTimer = setInterval(() => { refreshTimer = setInterval(() => {
getCpuUsage() getCpuUsage()
}, 2000) }, 2000)
})
}) })
// 组件卸载时停止定时器 // 组件卸载时停止定时器
@@ -137,7 +142,9 @@ onUnmounted(() => {
}) })
onActivated(() => { onActivated(() => {
nextTick(() => {
chartKey.value += 1 chartKey.value += 1
})
}) })
</script> </script>
+8
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(() => {
// 延迟启动,确保组件完全挂载
nextTick(() => {
getMemorgUsage() getMemorgUsage()
// 启动定时器 // 启动定时器
refreshTimer = setInterval(() => { refreshTimer = setInterval(() => {
getMemorgUsage() getMemorgUsage()
}, 3000) }, 3000)
})
}) })
// 组件卸载时停止定时器 // 组件卸载时停止定时器
@@ -143,7 +148,10 @@ onUnmounted(() => {
}) })
onActivated(() => { onActivated(() => {
// 使用nextTick确保DOM准备完成后再更新chartKey
nextTick(() => {
chartKey.value += 1 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(() => {
// 延迟启动,确保组件完全挂载
nextTick(() => {
getWeeklyData() getWeeklyData()
})
}) })
onActivated(() => { onActivated(() => {
// 使用nextTick确保DOM准备完成后再获取数据
nextTick(() => {
getWeeklyData() getWeeklyData()
})
}) })
</script> </script>