Vue+Sass实现动态换肤

言明,本文实现的动态换肤并非elementUi官网那种随意用ColorPicker实时更改主题的效果,而是为系统预设的几种主题事先配置颜色,然后线上触发更改主题的事件。

首先感谢luanxiyuan老师的博文引导。

此方案涉及Sass的map遍历、函数定义、map存取、混合器等相关知识,具体API详参官网https://www.sass.hk/docs/。

大概的思路就是给html根标签设置一个data-theme属性,通过js切换data-theme的属性值,sass根据此属性来判断使用对应主题变量。

具体实现步骤,以我的V5系统(dark、light)两种主题为例。

1.定义一个sass文件_themes.scss,存放系统中两种主题的相关颜色变量,文件位置可以放在style或者assets目录下,代码如下

//定义全局主题&颜色的map数组,鉴于V5只有白天和晚上的主题,此处仅定义这两种
//切记 所有颜色一式两份儿,务必保证key值统一,key值可以自定义,注意避免$%_之类的,
//与sass自有符号冲突,见文知意即可
//另外如果基于其他UI框架,如本项目基于element-ui,则只需设置一套dark主题,
//data-theme为dark时,样式引用dark
//data-theme为其他值时,自然就采用了elementui的默认样式
$themes: (
  light: (
    font_color1: rgb(196, 193, 193),
    font_color2: rgb(110, 109, 109),
    background_color1: rgb(255, 0, 21),
    background_color2: rgb(87, 87, 226),
    border_color1: rgb(231, 181, 181),
    border_color2: rgb(9, 255, 0)
  ),
  dark: (
    font_color1: rgb(226, 222, 222),
    font_color2: rgb(255, 255, 255),
    background_color1: rgb(87, 87, 226),
    background_color2: rgb(255, 0, 21),
    border_color1: rgb(9, 255, 0),
    border_color2: rgb(231, 181, 181)
  )
);

这里定义了一个map--$themes,分别存放对应主题的颜色变量集合。

注意,scss文件名建议用下划线开头,如_themes.scss,防止执行时被编译成单独的css文件,详参sass中文教程(3.1 sass文件导入)。

2.定义另外一个sass文件_handle.scss来操作1中的$theme变量(当然两个文件可以合并,分开写是想把配置和操作解耦),上代码:

@import "@/style/_themes.scss";
//此处用了sass的map遍历、函数、map存取、混合器等相关知识,
//详细API参考https://www.sass.hk/docs/

//遍历主题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);
  }
}
//获取字体颜色
@mixin font_color($color) {
  @include themeify {
    color: themed($color);
  }
}
//获取边框颜色
@mixin border_color($color) {
  @include themeify {
    border-color: themed($color);
  }
}

可以根据自己的使用场景自定义混入器,上面只定义了三个常用的,更改主题无非是更改背景&边框&字体等的颜色。

3.具体在vue中使用,直接引入对应混入器就好,取哪个颜色,传哪个key,就这么简单

<style lang="scss" scoped>
@import "@/style/_handle.scss";

p {
  font-size: 18px;
  @include font_color("font_color1");
  @include background_color("background_color1");
  @include border_color("border_color1");
}
</style>

到此,完毕了。至于怎么动态切换html的属性data-theme的值,那就驾轻就熟,js怎么干都行了,下面举例一种:

<template>
  <div>
    <p>这里是页面</p>
    <button @click="toggleTheme(1)">白天</button>
    <button @click="toggleTheme(0)">晚上</button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  methods: {
    toggleTheme(index) {
      window.document.documentElement.setAttribute(
        "data-theme",
        index ? "dark" : "light"
      );
    }
  }
};

彻底over,不要吐槽我配置的color,纯属举例。其他有不到的地方还请大神留言指正,非常感谢!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章