前言
上次写的换肤方案是比较适合于自己系统给定几套固定样式用于让用户切换。但是如果有需要让用户自定义颜色和图片的话,这套换肤方案会比较适合你。该文参考了该篇文章,并对其做了一些改进。做了持久化以及图片的切换。
应对需求
- 默认有几套主题色供用户选择
- 用户也可以自定义主题色
- 用户选定主题后需立即生效,无需重启项目或重新打包项目
一、准备工作
1.创建vue项目
2.安装插件(使用less)
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,代码如下
// 默认的主题颜色
@primaryColor: var(--primaryColor, #000);
@primaryTextColor: var(--primaryTextColor, green);
// 导出变量
:export {
name: 'less';
primaryColor: @primaryColor;
primaryTextColor: @primaryTextColor;
}
三、配置vue.config.js(配制了就可以使用less变量了)
const path = require("path");
module.exports = {
lintOnSave: false,
pluginOptions: {
"style-resources-loader": {
preProcessor: "less",
patterns: [
// 这个是加上自己的路径,不能使用(如下:alias)中配置的别名路径
path.resolve(__dirname, "./src/theme/style.less"),
],
},
},
};
当我们配置好vue.config.js文件后,就可以在项目的任何地方使用我们预先定义的less变量了,示例代码如下:
<style lang="less" scoped>
p {
color: @primaryTextColor;
}
</style>
四、配置几套可选主题
在/src/theme目录下新建model.js,编写自定义主题代码,代码如下:
// 一套默认主题以及一套暗黑主题
// 一套默认主题以及一套暗黑主题
export const themes = {
default: {
primaryColor: `${74}, ${144},${226}`,
primaryTextColor: `${74}, ${144},${226}`,
imgUrl:'logo-light.png'
},
dark: {
primaryColor: `${0},${0},${0}`,
primaryTextColor: `${0},${0},${0}`,
imgUrl:'logo-dark.png'
},
}
这里我们定义了两套默认主题,目的就是为了让用户能够在这两套主题中切换,其中主题颜色我们采用了rgba的写法,因为有可能我们需要在不用的地方使用同一主题色,但是透明度不一样
五、编写修改主题的方法
全局的颜色变量以及两套默认主题我们都编写好了,在这里我们已经实现了静态更改主题,即可以更改颜色,项目重新运行后便可生效。但是这还达不到我们的目的,我们需要动态更改主题,所以我们还需要编写一个能够动态更改主题的方法。
在/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) => {
localStorage.setItem("theme", themeName); // 保存主题到本地,下次进入使用该主题
const themeConfig = themes[themeName];
// 如果有主题名称,那么则采用我们定义的主题
if (themeConfig) {
// localStorage.setItem("primaryColor", themeConfig.primaryColor); // 保存主题色到本地
// localStorage.setItem("primaryTextColor", themeConfig.primaryTextColor); // 保存文字颜色到本地
changeStyle(themeConfig); // 改变样式
} else {
// 如果是没有主题名称,则去取本地中的颜色值拿出来用
let themeConfig = {
primaryColor: localStorage.getItem("primaryColor"),
primaryTextColor: localStorage.getItem("primaryTextColor"),
};
changeStyle(themeConfig);
}
};
六、配置vuex存储主题名
store/index下面配置即可
import Vue from "vue";
import Vuex from "vuex";
// import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
themeName: localStorage.getItem('themeName')
},
mutations: {
setTheme (state, data) {
state.themeName = data
}
},
actions: {},
modules: {},
// plugins: [
// createPersistedState({
// storage: window.localStorage,
// reducer (val) {
// // console.log(val);
// return val
// }
// })]
});
七、动态变换主题
修改我们的HelloWorld组件,演示如何动态修改主题。
测试代码如下:
<template>
<div class="hello">
<img :src="avatar" alt="" />
<div class="box-1"></div>
<div class="box-2"></div>
<p>我是测试文字</p>
<button @click="defaultTheme">默认主题</button>
<button @click="dark">暗黑主题</button>
<button @click="custom">自定义主题</button>
</div>
</template>
<script>
import { setTheme } from "../theme/theme";
import { mapState, mapMutations } from "vuex";
export default {
name: "HelloWorld",
computed: {
...mapState({
themeName: 'themeName'
}),
avatar () {
if (!this.themeName || this.themeName === 'zidingyi') {
// 这里应该去取自定义图片在服务器的路径,然后弄回来,这里先用本地的代替了
return require(`@/assets/images/logo-default.png`)
} else {
return require(`@/assets/images/logo-${this.themeName}.png`)
}
},
},
mounted () {
this.init(); // 初始化主题
},
methods: {
...mapMutations({
setTheme: 'setTheme'
}),
init () {
// setTheme("default"); // 初始化未默认主题
},
// 更改为默认主题
defaultTheme () {
localStorage.setItem('themeName', 'default')
this.setTheme('default')
setTheme("default");
},
// 更改为暗黑主题
dark () {
localStorage.setItem('themeName', 'dark')
this.setTheme('dark')
setTheme("dark");
},
// 更改为自定义主题
custom () {
let newColor = {
r: 12,
g: 33,
b: 234,
};
localStorage.setItem('themeName', 'zidingyi')
this.setTheme('zidingyi')
let newPrimaryColor = `${newColor.r},${newColor.g},${newColor.b}`;
localStorage.setItem("primaryColor", newPrimaryColor); // 将新的主题色存入本地
localStorage.setItem("primaryTextColor", newPrimaryColor); // 将新的主题色存入本地
setTheme();
},
},
};
</script>
<style scoped lang="less">
.hello {
display: flex;
flex-direction: column;
align-items: center;
.box-1 {
width: 50px;
height: 50px;
margin-bottom: 30px;
background: rgba(@primaryColor, 1);
}
.box-2 {
width: 50px;
height: 50px;
margin-bottom: 30px;
background: rgba(@primaryColor, 0.3);
}
p {
color: rgb(@primaryTextColor);
}
}
当我们进入页面是,会采用默认主题样式,然后用户可以点击按钮更改自定义的样式,并且会保存到本地和vuex中。 最终效果:
图片切换实现思路:
图片的路径主要使用computed来获取,这样子我们在更改主题的时候,vuex保存的主题值就会发生变化,而computed会监视该变化从而达到更换图片路径的效果