前言
- 每个网站都会有自己的一个主题色,本项目也会紧追时代潮流,增加换肤功能。
- 这里采用less+css变量结合的方式来实现。
- 本项目的皮肤(初步)有:极简白、神秘黑、活力橙、典雅黄、清新绿。
准备工作
- 上一节我们已经讲解了如何创建vue项目,本节我就直接使用了。
- 我们需要两个样式处理插件:
npm install style-resources-loader -D
npm install vue-cli-plugin-style-resources-loader -D
npm install less-loader@5.0.0 --save
npm install less --save
开工
新建style.less
- style.less用于配置全局样式。在项目src目录下新建theme文件夹,然后新建style.less,代码如下:
@primary: var(--primary, #4D85FF);
@primaryLight: var(--primaryLight, #ADC8FF);
@secondary: var(--primary, #CCCCCC);
@primaryText: var(--primaryText, #333333);
@secondaryText: var(--primaryText, #CCCCCC);
@activeText: var(--activeText, #4D85FF);
@backgroundColor: var(--backgroundColor, #F2F4FB);
@boxBackgroundColor: var(--backgroundColor, #ffffff);
:export {
name: "less";
primary: @primary;
primaryLight: @primaryLight;
secondary: @secondary;
primaryText: @primaryText;
secondaryText: @secondaryText;
activeText: @activeText;
backgroundColor: @backgroundColor;
boxBackgroundColor: @boxBackgroundColor;
}
配置vue.config.js
- 在项目根目录的vue.config.js文件添加如下配置:
const path = require("path")
module.exports = {
pluginOptions: {
"style-resources-loader": {
preProcessor: "less",
patterns: [
path.resolve(__dirname, "./src/theme/style.less"),
],
},
},
}
- 配置好vue.config.js文件后,就可以在全局使用我们预先定义的less变量了,示例代码如下:
<style lang="less">
div{
color: @primary;
}
</style>
配置主题
- 在/src/theme目录下新建models.js,编写自定义主题代码,代码如下:
- 这里我们定义了两套主题,可以根据自己需要添加即可。
export const themes = {
default: {
primary: `#4D85FF`,
primaryLight: `#ECF5FF`,
secondary: `#CCCCCC`,
primaryText: `#333333`,
secondaryText: `#CCCCCC`,
activeText: `#4D85FF`,
backgroundColor: `#F2F4FB`,
boxBackgroundColor: `#ffffff`,
},
dark: {
primary: '#4D81FF',
primaryLight: '#EAF5FF',
secondary: '#CCDCCC',
primaryText: '#323333',
secondaryText: '#CCACCC',
activeText: '#4D89FF',
backgroundColor: '#F2F1FB',
boxBackgroundColor: '#ff0fff'
}
};
封装切换主题方法
- 在/src/theme文件夹下新建theme.js文件,代码如下:
import { themes } from "./model";
const changeStyle = (obj) => {
for (let key in obj) {
document
.getElementsByTagName("body")[0]
.style.setProperty(`--${key}`, obj[key]);
}
};
export const setTheme = (themeName) => {
const themeConfig = themes[themeName];
if (!themeConfig) {
themeName = "default"
}
changeStyle(themeConfig);
localStorage.setItem("theme", themeName);
};
动态切换主题
- 准备工作做好了,在组件里使用setTheme即可实现切换主题:
<script setup>
import { setTheme } from '../theme/theme'
const test = () => {
setTheme('dark')
}
</script>
总结
- 至此,一键切换主题功能就做好了,上面所有代码仅作为测试,无实际作用,后面会不断完善细节。小伙伴们可以将自己的意见反馈发表到评论区,有合作想法的铁子欢迎私聊。。。