feat(admin): 添加深色主题支持
- 新增主题切换功能,支持浅色、深色和跟随系统三种模式 - 创建主题管理组合式函数 useTheme 和 CSS 变量定义 - 在所有视图组件中应用 CSS 变量以实现主题适配 - 在布局头部添加主题切换按钮,支持循环切换主题 - 更新 .gitignore 添加 .trae 文件忽略
This commit is contained in:
57
cwd-admin/src/composables/useTheme.ts
Normal file
57
cwd-admin/src/composables/useTheme.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import { ref } from 'vue';
|
||||
|
||||
export type Theme = 'light' | 'dark' | 'system';
|
||||
|
||||
const STORAGE_KEY = 'cwd_admin_theme';
|
||||
const theme = ref<Theme>('system');
|
||||
|
||||
export function useTheme() {
|
||||
function applyTheme() {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
const root = document.documentElement;
|
||||
const isDark =
|
||||
theme.value === 'dark' ||
|
||||
(theme.value === 'system' &&
|
||||
window.matchMedia('(prefers-color-scheme: dark)').matches);
|
||||
|
||||
if (isDark) {
|
||||
root.classList.add('dark');
|
||||
} else {
|
||||
root.classList.remove('dark');
|
||||
}
|
||||
}
|
||||
|
||||
function setTheme(newTheme: Theme) {
|
||||
theme.value = newTheme;
|
||||
localStorage.setItem(STORAGE_KEY, newTheme);
|
||||
applyTheme();
|
||||
}
|
||||
|
||||
function initTheme() {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
const stored = localStorage.getItem(STORAGE_KEY) as Theme | null;
|
||||
if (stored && ['light', 'dark', 'system'].includes(stored)) {
|
||||
theme.value = stored;
|
||||
} else {
|
||||
theme.value = 'system';
|
||||
}
|
||||
applyTheme();
|
||||
|
||||
// Listen for system changes
|
||||
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
// Remove existing listener to avoid duplicates if init is called multiple times (though it shouldn't be)
|
||||
mediaQuery.onchange = () => {
|
||||
if (theme.value === 'system') {
|
||||
applyTheme();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
theme,
|
||||
setTheme,
|
||||
initTheme
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user