vue 切换主题色
效果
切换主题色思路
- 使用 vuex 存放当前主题变量
- 根据主题动态切换根元素 #app 的类名
- 使用 less 函数与 less 变量控制相应主题色
main.js
导入主题文件
代码实现
目录结构
@/theme/themeFunction.less
用于写 less 函数,主要作用是提供主题样式
@/theme/theme.less
用于调用 less 函数,传入主题色
编码
- vuex 中存放主题色和修改主题色的方法
state: {
theme: 'blue' // 主题色
},
mutations: {
// 修改主题色
changeTheme (state, val) {
state.theme = val
}
}
- 给根元素动态赋类名
@/src/App.vue
<template>
<div id="app" :class="`${theme}_theme`">
<!-- ... -->
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState(['theme']),
},
}
</script>
- 编写 less 函数
@/theme/themeFunction.less
// themeFn接收多个参数
.themeFn(@themeColor, @themeColorHover, @themeColorActive, @themeColorDisable) {
// themeFn内部只书写与颜色相关的样式(以下样式仅供参考,具体代码需要结合项目修改)
// 推荐使用 !important
// 定义字体颜色,项目中有需要修改字体颜色的地方,直接加上 theme_font_color 类名即可
.theme_font_color {
color: @themeColor !important;
}
// 定义 elementUI 按钮颜色,项目中有需要修改按钮颜色的地方,直接加上 custom_btn_plain 类名即可
.custom_btn_plain {
&.el-button {
border-color: @themeColor !important;
color: @themeColor !important;
&:hover {
border-color: @themeColorHover !important;
background: @themeColorHover !important;
color: #ffffff !important;
}
&:active {
border-color: @themeColorActive !important;
background: @themeColorActive !important;
color: #ffffff !important;
}
}
&.is-disabled,
&.is-disabled:hover,
&.is-disabled:active {
border-color: @themeColorDisable !important;
background: @themeColorDisable !important;
}
}
}
- 调用 less 函数
@/theme/theme.less
// 注意需要导入themeFunction文件
@import './themeFunction.less';
// 蓝色主题
.blue_theme {
.themeFn(
rgba(21, 142, 238, 1),
rgba(34, 159, 247, 1),
rgba(1, 137, 217, 1),
rgba(34, 159, 247, 0.3)
);
}
// 红色主题
.red_theme {
.themeFn(
rgba(207, 0, 112, 1),
rgba(215, 0, 64, 1),
rgba(200, 8, 82, 1),
rgba(215, 0, 64, 0.3)
);
}
main.js
导入主题文件
// ...
import './theme/theme.less'
// ...
写在最后
以上仅为部分核心代码,换肤方案完整 demo 请参考我的github 仓库