1.要实现系统的一键换肤功能,首先要将颜色作为变量提取出来,并为两种主题配置颜色
variables.scss
//浅色主题
$light-theme: (
base-color: #000,
background-color: #ccc
);
//深色主题
$dark-theme: (
base-color: #fff,
background-color: #000
);
//定义映射集合
$themes: (
light-theme: $light-theme,
dark-theme: $dark-theme
);
//获取颜色并为当前主题色配置颜色
//字体颜色
@mixin base-color() {
@each $theme-name, $theme in $themes {
[data-theme = '#{$theme-name}'] & {
color: map-get($map: $theme, $key: base-color);
}
}
}
//背景色
@mixin base-background() {
@each $theme-name, $theme in $themes {
[data-theme = '#{$theme-name}'] & {
background: map-get($map: $theme, $key: background-color);
}
}
}
$font-size: 14px;
2.在 App.vue 中定义名为 “data-theme” 的变量,可设置此变量来配置主题颜色
<template>
<!--浅色-->
<router-view data-theme="light-theme"/>
<!--深色-->
<!--<router-view data-theme="dark-theme"/>-->
</template>
3.页面中的样式引入 variables 中定义好的变量,就可以自动按照当前主题切换样式了
<style lang="scss" scoped>
@import "../styles/variables.scss";
.main{
height: 100%;
@include base-color();
@include base-background();
font-size: $font-size;
}
</style>
4.如果在颜色较多的情况下,可以将获取颜色和设置颜色封装成函数
variable.scss
// 获取背景色下的变量颜色值
@function get-color-variable($variable-name) {
@return map-get($theme, $variable-name);
}
// 给当前主题色配置颜色变量
@mixin set-theme {
@each $theme-name, $theme in $themes {
// !global 把局部变量强升为全局变量
// 供get-color-variable函数中:map-get里 key 的使用
$theme: $theme !global;
[data-theme = '#{$theme-name}'] & {
@content;
}
}
}
在vue页面中的应用
<style lang="scss" scoped>
@import "../styles/variables.scss";
.main{
height: 100%;
font-size: $font-size;
@include set-theme {
color: get-color-variable('base-color');
background: get-color-variable('background-color');
}
}
</style>
5. Sass语法补充:使用@each循环
语法:
@each $var in <list or map>
1.循环一个list: 类名为 icon-20px 、icon-22px、icon-24px写他们的字体大小写法就可以如下:
$sizes:20px,22px,24px;
@each $size in $sizes {
.icon-#{$size} {
font-size:$size
}
}
2.循环一个map:类名为icon-primary、icon-success、icon-secondary等,但是他们的值又都是变量,写法如下
$blue: #0d6efd !default;
$gray-600: #6c757d !default;
$green: #52c41a !default;
$primary: $blue !default;
$secondary: $gray-600 !default;
$success: $green !default;
$theme-colors:(
"primary":$primary,
"secondary":$secondary,
"success":$success
);
@each $key,$val in $theme-colors {
.icon-#{$key} {
color: $val;
}
}
6. Sass语法补充:使用map-get
map-get( m a p , map, map,key) 函数的作用是根据 $key 参数,返回 $key 在 $map 中对应的 value 值。如果 $key 不存在 $map中,将返回 null 值。此函数包括两个参数:
$map:定义好的 map。
$key:需要遍历的 key。
假设要获取 facebook 键值对应的值 #3b5998,我们就可以使用 map-get() 函数来实现:
$social-colors: (
dribble: #ea4c89,
facebook: #3b5998,
github: #171515,
google: #db4437,
twitter: #55acee
);
.btn-dribble{
color: map-get($social-colors,facebook);
}