Element主题切换

1,465 阅读1分钟

全局变量

需要了解

CSS3如何定义使用全局变量

MDN中对于变量的描述:

Property names that are prefixed with --, like --example-name, represent custom properties that contain a value that can be used in other declarations using the var() function.

可以在html顶层元素定义全局变量供整个渲染文档使用。

:root {
  --COLOR-THEME:pink; // 也可以直接定义在html标签上
}
.el-button--primary {
  background-color: var(--COLOR-THEME, #409EFF) // -COLOR-THEME || #409EFF
}

--COLOR-THEME值发生改变,所有用到这个变量样式也会随之变化。

Element样式变量

如果你的项目中用的是SCSS,就可以通过覆盖element提供的变量值。在文件element-ui/packages/theme-chalk/src/common/var.scss可以查看对应变量。

image.png

实现

理解上面两个点,通过改变全局变量来实现主题切换的方式就很简单了。在项目中新建个样式文件:

$--color-primary: var(--COLOR-PRIMARY, #409EFF);
...

$--font-path: '~element-ui/lib/theme-chalk/fonts';
@import '~element-ui/packages/theme-chalk/src/index';