useThemeStore.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // src/stores/useThemeStore.ts
  2. import { defineStore } from "pinia";
  3. import { ref } from "vue";
  4. export const useThemeStore = defineStore("theme", () => {
  5. // 默认从 localStorage 读取,如果没有则根据系统偏好或默认 'light'
  6. const theme = ref<"light" | "dark">(
  7. (localStorage.getItem("theme") as "light" | "dark") || "dark",
  8. );
  9. const setTheme = (newTheme: "light" | "dark") => {
  10. theme.value = newTheme;
  11. localStorage.setItem("theme", newTheme);
  12. updateHtmlAttribute();
  13. };
  14. const toggleTheme = () => {
  15. setTheme(theme.value === "light" ? "dark" : "light");
  16. };
  17. // 更新 html 标签的 data-theme 属性,以便 CSS 选择器生效
  18. const updateHtmlAttribute = () => {
  19. if (theme.value === "dark") {
  20. document.documentElement.setAttribute("data-theme", "dark");
  21. } else {
  22. document.documentElement.removeAttribute("data-theme");
  23. }
  24. };
  25. // 初始化时执行一次
  26. updateHtmlAttribute();
  27. return {
  28. theme,
  29. setTheme,
  30. toggleTheme,
  31. };
  32. });