当前位置:   article > 正文

vue项目实现主题切换_vue项目前端切换主题

vue项目前端切换主题

已经做了一半的系统,突然提出要添加一个切换亮色和暗色主题的需求,第一反应想到的就是使用变量,总体思路就是:在html标签中添加自定义属性用来识别时亮色还是暗色,scss再通过这个属性来获取对应的颜色变量

一、创建存储变量的文件和处理变量的文件

1、主题变量文件(scss文件),主要用来保存要使用的变量颜色,分别对应亮色和暗色

$themes: (Bright: (
    moduleBackColor: #FFFFFF, // 模块底色
    backColor: #eff4f8,  // 页面底色
    mapColor: #FFFFFF,  // 地图背景颜色
    iconColor: #C5CEE8, // 图标颜色
), Dark: (
    moduleBackColor: #1B1A1F, // 模块底色
    backColor: #000000,  // 页面底色
    mapColor: #1B1A1F,  // 地图背景颜色
    iconColor: #494D60, // 图标颜色
));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

2、定义一个获取变量的函数文件 handle.scss,用于从主题色中取出具体的颜色

@import "./themes.scss";
// 切换主题,获取不同的主题色

@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;
        }
    }
}
//从主题色map中取出对应颜色
@function themed($key) {
    @return map-get($theme-map, $key);
}
//获取模块底色
@mixin module_background_color($color) {
    @include themeify {
        background-color: themed($color)!important;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

二、添加自定义属性来控制主题切换

	// 设置自定义属性,挂载默认的亮色主题
	window.document.documentElement.setAttribute('data-theme', 'Bright')
  • 1
  • 2

如果需要切换主题就修改自定义属性

//修改为暗色主题
window.document.documentElement.setAttribute('data-theme', 'Dark')
// 修改为亮色主题
window.document.documentElement.setAttribute('data-theme', 'Bright')
  • 1
  • 2
  • 3
  • 4

三、使用

在要使用的文件中引入这两个文件

@import '@/assets/styles/themes.scss';
@import '@/assets/styles/handle.scss';
  • 1
  • 2

然后就可以在文件中使用了

.main-table {
    @include module_background_color('moduleBackColor');
    height: 98%;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

四、效果

亮色
在这里插入图片描述

点击切换主题后变为暗色

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/133570
推荐阅读
相关标签
  

闽ICP备14008679号