38 lines
1.3 KiB
JavaScript
38 lines
1.3 KiB
JavaScript
|
// 使用 import.meta.glob 动态导入 themes 目录下的所有 .js 文件
|
||
|
// { eager: true } 表示同步导入,立即获取模块内容
|
||
|
const themeModules = import.meta.glob('./themes/*.js', { eager: true });
|
||
|
|
||
|
// 构建 themes 对象
|
||
|
export const themes = {};
|
||
|
for (const path in themeModules) {
|
||
|
// 从路径中提取主题名称 (e.g., './themes/default.js' -> 'default')
|
||
|
const themeName = path.replace('./themes/', '').replace('.js', '');
|
||
|
// 获取模块的默认导出 (即主题配置对象)
|
||
|
if (themeModules[path].default) {
|
||
|
themes[themeName] = themeModules[path].default;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// 主题切换函数
|
||
|
export function setTheme(themeName) {
|
||
|
const theme = themes[themeName] || themes.default // Fallback to default
|
||
|
if (!theme) {
|
||
|
console.error(`Theme "${themeName}" not found.`);
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
const root = document.documentElement
|
||
|
|
||
|
// 设置主题色变量
|
||
|
Object.keys(theme).forEach(key => {
|
||
|
root.style.setProperty(`--el-color-${key}`, theme[key])
|
||
|
})
|
||
|
|
||
|
// 设置主题类名
|
||
|
// 查找 body 上是否已有 theme- 开头的类
|
||
|
const currentThemeClass = Array.from(document.body.classList).find(cls => cls.startsWith('theme-'));
|
||
|
if (currentThemeClass) {
|
||
|
document.body.classList.remove(currentThemeClass);
|
||
|
}
|
||
|
document.body.classList.add(`theme-${themeName}`);
|
||
|
}
|