refactor(theme): 将主题逻辑提取到可复用组合式函数

- 从 App.vue 中移除内联主题管理代码
- 创建 useTheme 组合式函数集中处理主题状态、切换和系统主题监听
- 在 TopNav 组件中集成主题切换按钮和样式
- 保持原有功能不变,仅重构代码结构以提高可维护性
This commit is contained in:
2026-03-18 22:35:33 +08:00
parent f8094b40b7
commit bcfe39b32c
3 changed files with 111 additions and 52 deletions

View File

@@ -0,0 +1,52 @@
import { ref, watchEffect } from 'vue'
const isDark = ref(false)
// 初始化主题
const initTheme = () => {
const stored = localStorage.getItem('theme')
if (stored) {
isDark.value = stored === 'dark'
} else {
isDark.value = window.matchMedia('(prefers-color-scheme: dark)').matches
}
applyTheme()
}
// 应用主题到 DOM
const applyTheme = () => {
document.documentElement.classList.toggle('dark', isDark.value)
document.documentElement.setAttribute('data-theme', isDark.value ? 'dark' : 'light')
}
// 切换主题
const toggleTheme = () => {
isDark.value = !isDark.value
applyTheme()
localStorage.setItem('theme', isDark.value ? 'dark' : 'light')
}
// 监听系统主题变化
if (typeof window !== 'undefined') {
watchEffect((onCleanup) => {
const media = window.matchMedia('(prefers-color-scheme: dark)')
const handler = (e) => {
if (!localStorage.getItem('theme')) {
isDark.value = e.matches
applyTheme()
}
}
media.addEventListener('change', handler)
onCleanup(() => media.removeEventListener('change', handler))
})
}
// 自动初始化
initTheme()
export function useTheme() {
return {
isDark,
toggleTheme
}
}