diff --git a/src/App.vue b/src/App.vue index 1df0ab9..da4ac7d 100644 --- a/src/App.vue +++ b/src/App.vue @@ -4,10 +4,8 @@ import { useTheme } from "@/hooks/useTheme" import { ElNotification } from "element-plus" import zhCn from "element-plus/lib/locale/lang/zh-cn" -const { initTheme } = useTheme() - /** 初始化主题 */ -initTheme() +useTheme() /** 将 Element Plus 的语言设置为中文 */ const locale = zhCn diff --git a/src/hooks/useTheme.ts b/src/hooks/useTheme.ts index b870783..636231e 100644 --- a/src/hooks/useTheme.ts +++ b/src/hooks/useTheme.ts @@ -1,4 +1,4 @@ -import { ref } from "vue" +import { ref, watchEffect } from "vue" import { getActiveThemeName, setActiveThemeName } from "@/utils/cache/localStorage" const DEFAULT_THEME_NAME = "normal" @@ -31,14 +31,8 @@ const themeList: IThemeList[] = [ /** 正在应用的主题名称 */ const activeThemeName = ref(getActiveThemeName() || DEFAULT_THEME_NAME) -const initTheme = () => { - setHtmlClassName(activeThemeName.value) -} - const setTheme = (value: ThemeName) => { activeThemeName.value = value - setHtmlClassName(value) - setActiveThemeName(value) } /** 在 html 根元素上挂载 class */ @@ -46,7 +40,13 @@ const setHtmlClassName = (value: ThemeName) => { document.documentElement.className = value } +watchEffect(() => { + const value = activeThemeName.value + setHtmlClassName(value) + setActiveThemeName(value) +}) + /** 主题 hook */ export function useTheme() { - return { themeList, activeThemeName, initTheme, setTheme } + return { themeList, activeThemeName, setTheme } }