1. <template>
    2. <div @click="changeTheme" class="theme">
    3. <img :src="themepicture[0]" alt="" v-if="nowtheme == 'light'" />
    4. <img :src="themepicture[1]" alt="" v-if="nowtheme !== 'light'" />
    5. <span v-if="nowtheme == 'light'" class="word">晨间模式</span>
    6. <span v-if="nowtheme !== 'light'" class="word">夜间模式</span>
    7. </div>
    8. </template>
    9. <script lang="ts" setup>
    10. import { useDark, useToggle } from "@vueuse/core";
    11. import { ElMessage } from "element-plus";
    12. import { computed, nextTick, onMounted, ref } from "vue";
    13. let themepicture = [
    14. "src/assets/picture/light.png",
    15. "src/assets/picture/dark.png",
    16. ];
    17. let starttheme = computed(() => {
    18. if (window.localStorage.getItem("vueuse-color-scheme") == "auto") {
    19. return "light";
    20. } else if (window.localStorage.getItem("vueuse-color-scheme") == "dark") {
    21. return "dark";
    22. }
    23. });
    24. let nowtheme = ref(starttheme.value);
    25. const isDark = useDark({
    26. selector: "html", //class渲染的标签
    27. valueDark: "dark", //暗黑class名字
    28. valueLight: "light", //高亮class名字
    29. });
    30. const toggleDark = useToggle(isDark);
    31. let getThemePicture = function () {
    32. console.log(window.localStorage.getItem("vueuse-color-scheme"));
    33. console.log(window.localStorage.getItem("vueuse-color-scheme") == "light");
    34. console.log(starttheme.value);
    35. console.log(nowtheme.value);
    36. if (nowtheme.value == "dark") {
    37. } else if (nowtheme.value == "light") {
    38. }
    39. };
    40. getThemePicture();
    41. let changeThemePicture = function () {
    42. if (nowtheme.value == "dark") {
    43. nowtheme.value = "light";
    44. } else if (nowtheme.value == "light") {
    45. nowtheme.value = "dark";
    46. }
    47. };
    48. let changeTheme = function () {
    49. console.log(nowtheme.value);
    50. toggleDark();
    51. ElMessage.success("切换主题成功");
    52. changeThemePicture();
    53. };
    54. onMounted(() => {});
    55. </script>
    56. <style scoped>
    57. .theme img {
    58. width: 100%;
    59. height: 100%;
    60. }
    61. .word {
    62. font-size: 0.3vw;
    63. }
    64. </style>