vite scss 主题颜色切换

571 阅读1分钟

scss主题切换

对于项目中的主题颜色切换要求,可以用sass实现

sass安装

安装的具体方法以及配置可以查看 scss安装

配置

主题颜色配置文件

配置不同主题下的对应主题颜色

theme.scss

$bg-color: #567aaf;
$bg-color-dark: #000;

$themes: (
  light:(body-bg: $bg-color),
        dark: (body-bg: $bg-color-dark)
)

创建mixin文件

转换主题色的核心方法,如果看不懂,直接复制就可,需要引入上面的主题色配置文件

mixin.scss

@import "theme.scss";

@mixin themify($key: '') {
  @each $theme-name, $theme-map in $themes {

    [layout-theme="#{$theme-name}"] & {
      $theme-map: ()  !global;

      @each $key, $value in $theme-map {
        $theme-map: map-merge($theme-map, ($key: $value)) !global;
      }

      @content;

      $theme-map: null !global;
    }
  }
}
// 根据Key获取颜色的function
@function themed($key) {
  @return map-get($theme-map, $key);
}

使用mixin方法

可以直接引入到入口文件中(main.js),也可以导入到需要切换主题的组件中的style中

index.scss

@import "mixin.scss";

#app {
  @include themify($themes) {
    background-color: themed('body-bg'); // 参数为theme.scss中对于的主题色的key
  }
}

切换主题色

对于切换主题色的方法,

<script setup lang="ts">
// 通过该方法来控制对主题色的切换
window.document.documentElement.setAttribute("layout-theme", 'dark'); // dark为theme.scss中的主题色主题
</script>