1、先创建一个 _theme.scss文件 作为各类主题颜色的整理
$themes: (
light: (
//字体
font_color1: #414141,
font_color2: white,
$color-yellow: rgb(238, 255, 0),
//背景
background_color1: $color-red,
background_color2: #f0f2f5,
background_color3: red,
background_color4: #2674e7,
//边框
border_color1: #3d414a),
dark: (
//字体
font_color1: #a7a7a7,
font_color2: white,
//背景
background_color1: $color-light-gray,
$color-yellow: rgb(0, 255, 0),
background_color2: #283142,
background_color3: #1e6ceb,
background_color4: #323e4e,
//边框
border_color1: #3d414a));
//变量
$color-red: rgb(0, 0, 0);
// $color-yellow: rgb(83, 149, 235);
$color-white: white;
$color-light-gray: #818380;))
2、然后再创建一个 _handle.scss 文件 作为sass混合函数的存放 主要是哪个页面需要则引用即可
@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; } }
3、在页面中使用 , app.vue
html
<div class="btn"> <el-button type="warning" @click="theme('light')">浅色</el-button> <el-button type="danger" @click="theme('dark')">深色</el-button> </div>
js //换主题 theme(type) { // this.$store.commit("upDate", { themeType: type }); window.document.documentElement.setAttribute("data-theme", type); },
css
@import "@/assets/_handle.scss"; //修改任何元素都可以作为等级最高级 原理就是根据html标签的 [name]来判断主题类型进行修改 body { @include background_color(background_color4); .box { @include font_color("$color-yellow"); @include background_color($color-yellow); @include border_color("border_color1"); } .el-button { // @include background_color($color-yellow); &:hover { @include background_color($color-yellow); } } }
本文来自博客园,作者:书中枫叶,转载请注明原文链接:https://www.cnblogs.com/zy-mg/p/14632112.html