首页App.vue
<script setup lang="ts">
import LayOut from '@/components/Layout/Layout.vue';
import { zhCN, useDialog } from 'naive-ui';
import { onMounted } from 'vue';
import { useMainStore } from './stores/main';
const mainStore = useMainStore();onMounted(() => {mainStore.initDocumentTheme();let media = window.matchMedia('(prefers-color-scheme: dark)');media.addEventListener('change', (e) => {mainStore.changeTheme(e.matches?'dark':'light');//light});
});
</script>
<template><n-config-provider :locale="zhCN" :theme="mainStore.activeTheme"><n-loading-bar-provider><div class="w-100vw"><n-message-provider><n-dialog-provider><LayOut /></n-dialog-provider></n-message-provider></div></n-loading-bar-provider></n-config-provider>
</template><style>
@import "@/assets/base.css";
::-webkit-scrollbar {width: 5px;height: 5px;background-color: transparent;
}
::-webkit-scrollbar-thumb{width: 5px;@apply bg-gray-400/40;border-radius: 10px;
}
</style>
主题颜色切换使用了n-switch
<n-switch :value="mainStore.isActiveDarkTheme" size="large" :on-update:value="handleThemeSwitchUpdateChange"><template #checked-icon><n-icon :component="Moon" /></template><template #unchecked-icon><n-icon :component="SunnySharp" /></template></n-switch>
回调函数是handleThemeSwitchUpdateChange
const handleThemeSwitchUpdateChange = () => {mainStore.toggleTheme();
ts中的自定义类对象mainStore
toggleTheme() {const theme = this.theme ==='dark'? 'light':'dark';this.changeTheme(theme);},changeTheme(theme:'dark' | 'light') {if (theme === 'dark') {//这个设置html外围的颜色document.documentElement.classList.add('dark');document.documentElement.style.colorScheme = 'dark';} else {//这个设置html外围的颜色document.documentElement.classList.remove('dark');document.documentElement.style.colorScheme = '';}// 设置网页的配色方案为dark this.theme = theme;//这个设置navie-ui的空间localStorage.theme = theme;},