refactor: 使用 watchEffect 来收集主题相关的副作用 (#64)

This commit is contained in:
betterwusy
2023-03-28 14:16:17 +08:00
committed by GitHub
parent 9e0bf64254
commit 6d0ef20b0b
2 changed files with 9 additions and 11 deletions

View File

@@ -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<ThemeName>(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 }
}