跟着 ElementPlus 学主题定制
8 分钟
2022-07-15
最近更新于: 2022-07-15 00:00:00
前言
最近看了下 ElementPlus
的源码,发现其主题定制挺有意思的,这篇文章就跟大家揭开一角。
主题定制方案
CSS 优先级覆盖
利用CSS 的权重进行样式覆盖,达到主题切换的效果
CSS 动态增减
动态加载样式
1、直接切换样式库。
2、通过JavaScript
来切换样式规则。
CSS 变量
通过定制变量,达到主题定制。
1、通过预处理器来定制变量。
2、通过 Var
来定制变量
ElementPlus 就基于 Var
来实现主题的定制,下面详细介绍下它的解决方案。
ElementPlus 主题定制
ElementPlus 主题定制我简单分为变量配置
,SCSS 函数
、变量生成
、主题切换
四个部分来开展。
变量配置
变量划分品牌色、背景色、字体颜色、边框颜色、填充颜色、遮罩颜色、覆盖颜色、字体、字体大小、字重、行高、层级、边框大小、边框弧度、边框样式、间距、禁用、阴影、过渡等等。这些都是设计的基础元素,详细可以看看我之前这篇设计原则文章。
以下变量经过改造,适配于项目:
SCSS 函数
ElementPlus 利用了强大的SCSS
函数来生成类名,并且使用BEM
规范来规范类名命名,使得整体显得非常干净利落。下面介绍其中一些常用的函数(一些基础概念详见官方文档)。
变量生成
1、生成SCSS
变量,利用map.merge
来合并之前配置变量
2、利用SCSS
函数生成Var
变量
主题切换
1、异步加载所有的主题
2、根据当前系统,匹配不同的主题
3、提高 useTheme
函数,手动切换主题,实现按需加载主题
最终结果
默认和暗黑主题Var
变量
总结
本来通过剖析 ElementPlus 源码来解析其主题定制方案,主要涉及变量配置
、SCSS函数
、变量生成
、主题切换
四步,达到主题定制的效果。此外ElementPlus 广泛使用 SCSS
,通过封装了一系列SCSS函数
和 Mixin
,结合命名空间、BEM规范等构建了一个完整的 CSS 工程化系统,值得我们更加深入的学习和应用。