theme.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { toRefs, shallowReadonly, ShallowRef } from 'vue'
  2. import { AppTheme } from '@/constants/theme'
  3. import { VueStore } from '../base'
  4. import WebStorage from '@/utils/storage/base'
  5. import plus from '@/utils/h5plus'
  6. interface StoreState {
  7. appTheme: ShallowRef<AppTheme>;
  8. }
  9. const store = new (class extends VueStore<StoreState>{
  10. constructor() {
  11. const storage = new WebStorage<AppTheme>(localStorage, 'appTheme', AppTheme.Default)
  12. const state: StoreState = {
  13. appTheme: storage.getRef()
  14. }
  15. super(state)
  16. document.addEventListener('DOMContentLoaded', this.loadTheme, false)
  17. }
  18. /**
  19. * 加载主题
  20. */
  21. private loadTheme = () => {
  22. const theme = this.state.appTheme
  23. this.setStatusBarTheme(theme)
  24. document.documentElement.setAttribute('theme', theme)
  25. document.removeEventListener('DOMContentLoaded', this.loadTheme)
  26. }
  27. /**
  28. * 设置状态栏主题色
  29. * @param theme
  30. */
  31. private setStatusBarTheme = (theme: AppTheme) => {
  32. switch (theme) {
  33. case AppTheme.Default:
  34. case AppTheme.Dark: {
  35. plus.setStatusBarStyle('light')
  36. break
  37. }
  38. default: {
  39. plus.setStatusBarStyle('dark')
  40. }
  41. }
  42. }
  43. actions = {
  44. /** 设置主题 */
  45. setTheme: (key: keyof typeof AppTheme) => {
  46. const theme = AppTheme[key]
  47. this.setStatusBarTheme(theme)
  48. document.documentElement.setAttribute('theme', theme)
  49. this.state.appTheme = theme
  50. }
  51. }
  52. })
  53. export function useThemeStore() {
  54. return shallowReadonly({
  55. ...toRefs(store.state),
  56. ...store.actions,
  57. ...store.methods,
  58. })
  59. }