注明:在vue项目中,越来越多的客户要求可以自定义主题的颜色,使用scss改主题颜色是一个不错的方法,那下面简单说下scss怎么实现主题切换。
一.简单版本
1.定义方法,循环遍历映射集合,生成对应样式表
@import "./_themes.scss";
//遍历主题map
@mixin themeify {
@each $theme-name, $theme-map in $themes {
//!global 把局部变量强升为全局变量
$theme-map: $theme-map !global;
//判断html的data-theme的属性值 #{}是sass的插值表达式
//& sass嵌套里的父容器标识 @content是混合器插槽,像vue的slot
[data-theme="#{$theme-name}"] & {
@content;
}
}
}
//声明一个根据Key获取颜色的function
@function themed($key) {
@return map-get($theme-map, $key);
}
//获取背景颜色
@mixin background_color($color) {
@include themeify {
background-color: themed($color)!important;
}
}
//获取字体颜色
@mixin font_color($color) {
@include themeify {
color: themed($color)!important;
}
}
//获取边框颜色
@mixin border_color($color) {
@include themeify {
border-color: themed($color)!important;
}
}
2.定义颜色表
//当HTML的data-theme为dark时,样式引用dark
//data-theme为其他值时,就采用组件库的默认样式
//这里我只定义了两套主题方案,想要再多只需在`$themes`里加就行了
//注意一点是,每套配色方案里的key可以自定义但必须一致,不然就会混乱
$themes: (
light: (
//字体
font_color1: #414141,
font_color2: white,
//背景
background_color1: #fff,
background_color2: #f0f2f5,
background_color3: red,
background_color4: #2674e7,
//边框
border_color1: #3d414a,
),
dark: (
//字体
font_color1: white,
font_color2: #414141,
//背景
background_color1: #1b2531,
background_color2: #283142,
background_color3: #1e6ceb,
background_color4: #323e4e,
//边框
border_color1: #3d414a,
)
);
3.使用动态绑定data-theme 并且定义class
<template>
<div class="common-util" :data-theme="type">
<span @click="theme('iview')">默认</span>
<span @click="theme('light')">浅色</span>
<span @click="theme('dark')">深色</span>
</div>
</template>
<script>
export default {
data() {
return {
type: "default",
};
},
methods: {
//换主题
theme(type) {
this.$store.commit("ACTIVE", type); //存在vuex
this.type = this.$store.state.type;
window.document.documentElement.setAttribute("data-theme", type);
},
},
};
</script>
<style lang="scss" scoped>
@import "../assets/scss/_handle.scss"; //必须引入
span {
display: block;
padding: 2%;
}
.common-util {
font-size: 18px;
@include font_color("font_color1");
@include background_color("background_color1");
@include border_color("border_color1");
}
</style>