前端利用scss实现一键换肤功能

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>

猜你喜欢

转载自blog.csdn.net/wytraining/article/details/109676970