当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue结合sass进行主题切换(完整简单示例展示)

vue结合sass进行主题切换(完整简单示例展示)

2020年07月11日  | 移动技术网IT编程  | 我要评论

包含两个scss文件,一个存主题样式,一个控制主题切换

测试页面

<template>
  <div>
    <p>测试
      <button @click="toggleTheme(1)">蓝色</button>
    <button @click="toggleTheme(0)">红色</button>
    </p>
    
  </div>
</template>
<script>
export default {
  name: "HelloWorld",
  methods: {
    toggleTheme(index) {
      console.log(window.document.documentElement)
      //修改html的主题
      window.document.documentElement.setAttribute(
        "data-theme",
        index ? "dark" : "light"
      );
    }
  }
};
</script>
<style scoped lang="scss">

@import '@/assets/css/_handle.scss';
p{
  font-size: 18px;
  width: 100%;
  height: 100vh;
  text-align: center;
  @include font_color('font_color1');
  @include background_color("background_color1");
  @include border_color("border_color1");
}
</style>

主题scss页面,_themes.scss

//定义全局主题&颜色的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)
  )
);

主题控制scss文件_handle.scss

@import "@/assets/css/_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);
  }
}

本文地址:https://blog.csdn.net/DXL131795/article/details/107234675

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网