项目中提到了全局切换主题的需求。在项目开发中切换主题用到主要技术有Scss,Vuex。
一、Scss部分
实现思路:因为要实现主题的切换,所以在开发组件中涉及到主题的地方,要提取一些公用的变量,不要直接写死样式值。但是如果只是定义一些变量的话,只是完成控制颜色等值的提取。还是无法实现用户在前端点击对应的主题,即可批量的切换颜色的需求。因此必定要用到映射表来批量替换提取的这些控制变量。所以根据以上思路实现如下:
定义变量以及映射表
// 默认主题
$default-theme : (
base-color: #ddd,
border-color: #000
);
//红色主题
$red-theme : (
base-color: red,
border-color: red
);
//定义映射集合
$themes: (
default-theme: $default-theme,
red-theme: $red-theme
);
定义方法,循环遍历映射集合,生成对应样式表
@mixin base-background(){
@each $themename , $theme in $themes {
[data-theme = '#{$themename}'] & {
background: map-get($map: $theme, $key: base-color )
}
}
}
在组件中,引入公共文