themeSwitch.html 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. {{define "component/themeSwitchTemplate"}}
  2. <template>
  3. <a-switch size="small" :default-checked="themeSwitcher.isDarkTheme"
  4. @change="themeSwitcher.toggleTheme()">
  5. </a-switch>
  6. </template>
  7. {{end}}
  8. {{define "component/themeSwitcher"}}
  9. <script>
  10. function createThemeSwitcher() {
  11. const isDarkTheme = localStorage.getItem('dark-mode') === 'true';
  12. const theme = isDarkTheme ? 'dark' : 'light';
  13. document.querySelector('body').setAttribute('class', theme)
  14. return {
  15. isDarkTheme,
  16. get currentTheme() {
  17. return this.isDarkTheme ? 'dark' : 'light';
  18. },
  19. toggleTheme() {
  20. this.isDarkTheme = !this.isDarkTheme;
  21. localStorage.setItem('dark-mode', this.isDarkTheme);
  22. document.querySelector('body').setAttribute('class', this.isDarkTheme ? 'dark' : 'light')
  23. },
  24. };
  25. }
  26. const themeSwitcher = createThemeSwitcher();
  27. Vue.component('theme-switch', {
  28. props: [],
  29. template: `{{template "component/themeSwitchTemplate"}}`,
  30. data: () => ({ themeSwitcher }),
  31. });
  32. </script>
  33. {{end}}