vue基于scss的动态切换主题颜色

根据预设的配色方案,在前端动态切换系统主题颜色

大概的思路就是给html根标签设置一个data-theme属性,然后通过js切换data-theme的属性值,Scss根据此属性来判断使用对应主题变量。这里可以选择持久化Vux或接口来保存用户选择的主题。

具体实现

  1. 新建themes.scss文件

这里只是做示例就写两个样式参考,更多的自己补充一下

$themes: (Red: ( //整体主色调/菜单栏背景/图标.按钮主色/悬停状态
    mainColor: #D6000F, //主题色
    titleColor: #5f95cc, //默认字体色/二级信息字体色
    ),
  Blue: ( //整体主色调/菜单栏背景/图标.按钮主色/悬停状态
    mainColor: #409EFF, //菜单选中背景色/点击状态/文字,按钮按下
    titleColor: #d64e18, //列表背景色
    ),
);
  1. 新建handle.scss文件操作

themeify方法用于获取HTML的 data-theme值。
themed方法用于根据HTML的 data-theme值及调用者传过来的key去 themes.scss里获取相应的颜色。

@import "./themes.scss";
//切换主题时 获取不同的主题色值
@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;
        }
    }
}


//从主题色map中取出对应颜色
@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;
    }
}

  1. 在vue页面中使用

```html
<template>
  <div class="my--demo">
      <Dropdown>
        <Button type="primary">
         主题切换
          <i class="el-icon-arrow-down el-icon--right"></i>
        </Button>
        <DropdownMenu slot="dropdown">
          <DropdownItem @click.native="theme('normal')">默认</DropdownItem>
          <DropdownItem @click.native="theme('Red')">红色</DropdownItem>
          <DropdownItem @click.native="theme('Blue')">蓝色</DropdownItem>
        </DropdownMenu>
      </Dropdown>
      <div class="common-util">测试主题变化</div>
  </div>
</template>
<script>
export default {
    
    
  name: 'themeDemo',
  methods: {
    
    
    //换主题
    theme(type) {
    
    
      window.document.documentElement.setAttribute('data-theme', type)
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/styles/base/_handle.scss';
.common-util {
    
    
  font-size: 18px;
  height: 100px;
  margin-top: 20px;
  @include font_color('titleColor');
  @include background_color('mainColor');
  @include border_color('mainColor');
}
</style>

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42068550/article/details/121538102