众所周知,sass可以用一些函数去编写css,下面,我记录一次实际项目中的运用。
首先新建一个theme.scss文件去存放主题色的map:
/**
颜色对应
$_040508_6: rgba(255, 255, 255, 0.6),
$_040508: #e6e6e6,
**/
$themes: (
light: (
$_040508_6: rgba(4, 5, 8, 0.6),
$_040508: #040806,
),
dark: (
$_040508_6: rgba(255, 255, 255, 0.6),
$_040508: #e6e6e6,
),
);
然后再新建一个handle.scss文件去使用它:
@import "theme.scss";
@mixin themeify {
@each $theme-name, $theme-map in $themes {
$theme-map: $theme-map !global;
.appBox[data-theme="#{$theme-name}"] & {
@content;
}
}
}
@function themed($key) {
@return map-get($theme-map, $key);
}
//背景
@mixin background_color($color) {
@include themeify {
background-color: themed($color);
}
}
//背景
@mixin background_color($color,$isimportant:-1) {
@include themeify {
@if ($isimportant > 0) {
background-color: themed($color) !important;
}@else {
background-color: themed($color);
}
}
}
如上图,主要是用了themeify 和 themed两个函数,themeify的意思是循环themes.scss中定义的变量$themes,并且将$theme-map定义为全局的。 themed主要就是获取上面定义的map。
.appBox[data-theme="#{$theme-name}"] 意思是在class name 是appBox的元素 如果有一个属性是light或者dark 就让样式生效,具体看用法:
<div
class="w100 appBox"
:class="`font-${locale} theme_${theme}`"
:data-theme="theme"
></div>
我们在vue文件中怎么引用定义的样式呢?
比如说背景色,如上图定义一个mixin background_color,
然后在vue文件的scss样式中用 @include background_color($_040508) 就可以了;