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

This commit is contained in:
betterwusy 2023-03-28 14:16:17 +08:00 committed by GitHub
parent 9e0bf64254
commit 6d0ef20b0b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 11 deletions

View File

@ -4,10 +4,8 @@ import { useTheme } from "@/hooks/useTheme"
import { ElNotification } from "element-plus" import { ElNotification } from "element-plus"
import zhCn from "element-plus/lib/locale/lang/zh-cn" import zhCn from "element-plus/lib/locale/lang/zh-cn"
const { initTheme } = useTheme()
/** 初始化主题 */ /** 初始化主题 */
initTheme() useTheme()
/** 将 Element Plus 的语言设置为中文 */ /** 将 Element Plus 的语言设置为中文 */
const locale = zhCn const locale = zhCn

View File

@ -1,4 +1,4 @@
import { ref } from "vue" import { ref, watchEffect } from "vue"
import { getActiveThemeName, setActiveThemeName } from "@/utils/cache/localStorage" import { getActiveThemeName, setActiveThemeName } from "@/utils/cache/localStorage"
const DEFAULT_THEME_NAME = "normal" const DEFAULT_THEME_NAME = "normal"
@ -31,14 +31,8 @@ const themeList: IThemeList[] = [
/** 正在应用的主题名称 */ /** 正在应用的主题名称 */
const activeThemeName = ref<ThemeName>(getActiveThemeName() || DEFAULT_THEME_NAME) const activeThemeName = ref<ThemeName>(getActiveThemeName() || DEFAULT_THEME_NAME)
const initTheme = () => {
setHtmlClassName(activeThemeName.value)
}
const setTheme = (value: ThemeName) => { const setTheme = (value: ThemeName) => {
activeThemeName.value = value activeThemeName.value = value
setHtmlClassName(value)
setActiveThemeName(value)
} }
/** 在 html 根元素上挂载 class */ /** 在 html 根元素上挂载 class */
@ -46,7 +40,13 @@ const setHtmlClassName = (value: ThemeName) => {
document.documentElement.className = value document.documentElement.className = value
} }
watchEffect(() => {
const value = activeThemeName.value
setHtmlClassName(value)
setActiveThemeName(value)
})
/** 主题 hook */ /** 主题 hook */
export function useTheme() { export function useTheme() {
return { themeList, activeThemeName, initTheme, setTheme } return { themeList, activeThemeName, setTheme }
} }