| 1234567891011121314151617181920212223242526272829303132333435363738 |
- // src/stores/useThemeStore.ts
- import { defineStore } from "pinia";
- import { ref } from "vue";
- export const useThemeStore = defineStore("theme", () => {
- // 默认从 localStorage 读取,如果没有则根据系统偏好或默认 'light'
- const theme = ref<"light" | "dark">(
- (localStorage.getItem("theme") as "light" | "dark") || "dark",
- );
- const setTheme = (newTheme: "light" | "dark") => {
- theme.value = newTheme;
- localStorage.setItem("theme", newTheme);
- updateHtmlAttribute();
- };
- const toggleTheme = () => {
- setTheme(theme.value === "light" ? "dark" : "light");
- };
- // 更新 html 标签的 data-theme 属性,以便 CSS 选择器生效
- const updateHtmlAttribute = () => {
- if (theme.value === "dark") {
- document.documentElement.setAttribute("data-theme", "dark");
- } else {
- document.documentElement.removeAttribute("data-theme");
- }
- };
- // 初始化时执行一次
- updateHtmlAttribute();
- return {
- theme,
- setTheme,
- toggleTheme,
- };
- });
|