一、Ant Design
- 步骤1: 通过 antd-theme-generator 生成less变量:
- 步骤2: 动态修改HTML的 data-theme 属性。
- 步骤3: 使用CSS变量或全局状态管理主题。
// 动态切换主题 const changeTheme = (theme) => { document.documentElement.setAttribute('data-theme', theme); };
二、elementUI
方法一:使用CSS变量(推荐)
这是最灵活且性能较好的方式,适用于现代浏览器:
-
定义主题变量:
:root { --el-color-primary: #409EFF; --el-color-success: #67C23A; /* 其他主题变量... */ } .theme-dark { --el-color-primary: #3375b9; --el-color-success: #4e8e2f; /* 其他主题变量... */ }
-
动态切换类名:
// 切换为暗色主题 document.body.classList.add('theme-dark'); // 切换回默认主题 document.body.classList.remove('theme-dark');
方法二:使用官方主题工具
这是最灵活且性能较好的方式,适用于现代浏览器:
-
使用element-theme工具:
npm i element-theme -g npm i element-theme-chalk -D
-
生成多套主题文件:
et -c ./vars-dark.css et -c ./vars-light.css
-
动态加载主题:
function loadTheme(themeName) { const link = document.getElementById('theme-style'); if (link) { link.href = `./theme/${themeName}/index.css`; } else { const style = document.createElement('link'); style.id = 'theme-style'; style.rel = 'stylesheet'; style.href = `./theme/${themeName}/index.css`; document.head.appendChild(style); } } // 使用 loadTheme('dark'); // 或 'light'
方法三:使用SCSS变量覆盖
-
创建主题文件:
// theme-dark.scss $--color-primary: #3375b9; $--color-success: #4e8e2f; /* 导入Element UI默认样式 */ @import "~element-ui/packages/theme-chalk/src/index";
-
编译不同主题并动态加载(类似方法二)
方法四:使用Vue插件动态切换
创建一个Vue插件来管理主题:
// themePlugin.js
const ThemePlugin = {
install(Vue, options) {
Vue.prototype.$theme = {
set(themeName) {
const head = document.head;
const link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = `/path/to/${themeName}.css`;
link.id = 'element-theme';
const oldLink = document.getElementById('element-theme');
if (oldLink) {
head.removeChild(oldLink);
}
head.appendChild(link);
}
}
}
}
// main.js
import ThemePlugin from './themePlugin';
Vue.use(ThemePlugin);
// 使用
this.$theme.set('dark');
注意事项
-
性能考虑:CSS变量方式性能最好,但兼容性要求较高;动态加载CSS文件方式兼容性好但可能有短暂样式闪烁
-
预加载主题:可以预先加载所有主题CSS文件,通过类名控制显示哪个
-
持久化存储:建议将用户选择的主题存储在localStorage中
-
Element Plus:如果是使用Element Plus(Vue 3),官方提供了更完善的主题切换方案