- 主要代码
代码如下:
//颜色数据
const colorStyle = {
normal: [
{
name: '--globalBgC',
value: '#fff',
},
],
black: [
{
name: '--globalBgC',
value: 'blue',
},
],
};
//切换方法
export const changeColorStyle = (skin) => {
if (skin === 'normal') {
colorStyle.normal.forEach((item) => {
document.documentElement.style.setProperty(item.name, item.value);
});
} else {
colorStyle.black.forEach((item) => {
document.documentElement.style.setProperty(item.name, item.value);
});
}};
**colorStyle 保存两种模式的颜色数据,changeColorStyle 为切换主题方法。**核心就一句
**document.documentElement.style.setProperty(item.name, item.value),设置全局****颜色变量。**这里建议单独建个文件维护。同时本文默认在vue使用,但是只是环境是vue,在原生或者其他框架中都可以无缝切换。
- 使用方法
先在全局组件中导入方法import { changeColorStyle } from '@/util/colorStyle.js';(路径自定义)。并立即执行该方法。
created() {
changeColorStyle('normal');
window._currentSkin = 'normal';//保存当前主题
}
css使用变量:
<style>
.rootBgColor{
background-color:var(--globalBgC)
}
</style>
切换主题方法:
changeSkin() {
if (window._currentSkin === 'normal') {
window._currentSkin = 'black';
} else {
window._currentSkin = 'normal';
}
changeColorStyle(window._currentSkin);
// this.$bus.$emit("changeSkin", window._currentSkin);//在vue中可以通过此方法监听换肤
事件,并做一些自己的特殊化处理。例如:有些模块不只是切换颜色,就可以自定义处理
}
如果想保存当前主题的话,也很简单,不管是前端还是后端保存。先取到保存的主题再处理就行了。同时这种方法的兼容性也很好,代码简单方便修改。