refactor: 使用 watchEffect 来收集主题相关的副作用 (#64)
This commit is contained in:
@@ -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 }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user