Vue主题切换

850 阅读1分钟

创建主题切换颜色库文件

1.声明变量 defaultthemedefault-theme及deepBlue-theme,这里我只需要两种主题,如果需要更多创建即可。

$default-theme:(header-top-bgcolor:#161e43,table-word:#fff,);
$deepBlue-theme:(header-top-bgcolor:#006272,table-word:#666,);
主题中声明了头部背景色,及文字颜色变量

2.初始化方法以备调用

$themes: (default-theme: $default-theme,
  deepBlue-theme: $deepBlue-theme);
// 遍历主题map 获取HTML的data-theme值
@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
// 用于根据HTML的data-theme值及调用者传过来的key去_themes.scss里获取相应的颜色
@function themed($key) {
  @return map-get($theme-map, $key);
}

// 获取table字体大小
@mixin eltable_size($size) {
  @include themeify {
    font-size: themed($size) !important;
  }
}

// 获取背景颜色
@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: themed($color) !important;
  }
}

3.点击事件初始化改变主题

    // 切换主题 存储到缓存和store中,方便不同界面监听主题切换。
changeTheme() {
  let theme = localStorage.getItem("znyd1-theme");
    if (!theme || theme === "default-theme") {
       window.document.documentElement.setAttribute(
          "data-theme",
          "deepBlue-theme"
        );
        this.$store.commit("SET_THEME",'deepBlue-theme')
        localStorage.setItem("my-theme", "deepBlue-theme");
      } else if (!theme || theme === "deepBlue-theme") {
        window.document.documentElement.setAttribute(
          "data-theme",
          "default-theme"
        );
        this.$store.commit("SET_THEME",'default-theme')
        localStorage.setItem("my-theme", "default-theme");
      }
 },

4.初始化进入页面默认主题,未初始化会导致界面白色, 或其他颜色。

if (localStorage.getItem('my-theme') == "default-theme") {
  window.document.documentElement.setAttribute(
    "data-theme",
    "default-theme"
  );
  localStorage.setItem('v-theme', 'default-theme');
} else if (localStorage.getItem('my-theme') == "deepBlue-theme") {
  window.document.documentElement.setAttribute(
    "data-theme",
    "deepBlue-theme"
  );
  localStorage.setItem('my-theme', 'deepBlue-theme');
} else {
  window.document.documentElement.setAttribute(
    "data-theme",
    "default-theme"
  );
  localStorage.setItem('my-theme', 'default-theme');
}

5.界面中或初始化样式表index.scss调用

@import "@/styles/element-my.scss";
@include background_color("header-top-bgcolor");

私密原因,部分效果展示

default.png

deep.png