refactor: 将多主题功能从 pinia 抽离为 hook

This commit is contained in:
pany
2022-10-17 15:04:27 +08:00
parent e41d1f21a5
commit 281a7bebbf
6 changed files with 54 additions and 53 deletions

44
src/hooks/useTheme.ts Normal file
View File

@@ -0,0 +1,44 @@
import { ref } from "vue"
import { getActiveThemeName, setActiveThemeName } from "@/utils/cache/localStorage"
interface IThemeList {
title: string
name: ThemeName
}
/** 注册的主题名称, 其中 normal 是必填的 */
export type ThemeName = "normal" | "dark"
/** 主题 hook */
export function useTheme() {
/** 主题列表 */
const themeList: IThemeList[] = [
{
title: "默认",
name: "normal"
},
{
title: "黑暗",
name: "dark"
}
]
/** 正在应用的主题名称 */
const activeThemeName = ref<ThemeName>(getActiveThemeName() || "normal")
const initTheme = () => {
setHtmlClassName(activeThemeName.value)
}
const setTheme = (value: ThemeName) => {
activeThemeName.value = value
setHtmlClassName(activeThemeName.value)
setActiveThemeName(activeThemeName.value)
}
/** 在 html 根元素上挂载 class */
const setHtmlClassName = (value: ThemeName) => {
document.documentElement.className = value
}
return { themeList, activeThemeName, initTheme, setTheme }
}