webpack-theme-color-replacer原理是通过获取到配置数组里的颜色值,在触发换色方法时,elementui使用的颜色值存在与配置表中颜色一致的颜色,则改颜色会被替换成新的颜色值。
若是自定义的css文件,需要配置css文件路径
若是需要修改除主题色外的颜色,则配置颜色数组需传入对应的默认色,在触发修改颜色方法前,通过将主题色的十六进制转为RGBA,然后通过规律加减颜色通道生成其它色,位置需要一一对应
一、安装webpack-theme-color-replacer
npm install ---save webpack-theme-color-replacer
二、在vue.config.js配置
const ThemeColorReplacer = require("webpack-theme-color-replacer");
const forElementUI = require("webpack-theme-color-replacer/forElementUI");
const { defineConfig } = require("@vue/cli-service");
module.exports = defineConfig({
transpileDependencies: true,
chainWebpack: config => {
// 自定义换肤
config
.plugin("webpack-theme-color-replacer")
.use(ThemeColorReplacer)
.tap(options => {
const matchColors = []
const data = ['#409eff']//这里可传入多个颜色,后续匹配到的会同步修改
data.forEach(item => {
matchColors.push(...forElementUI.getElementUISeries(item))
})
options[0] = {
fileName: "css/theme-colors-[contenthash:8].css",
matchColors,
changeSelector: forElementUI.changeSelector,
//项目其它css文件,存在与主题色一样的颜色也会更改,否则不会改变
externalCssFiles: ["./src/assets/css/index.css"],
isJsUgly: process.env.NODE_ENV !== "development"
};
return options;
});
}
});
三、创建utils/thems.js
import client from "webpack-theme-color-replacer/client";
import forElementUI from "webpack-theme-color-replacer/forElementUI";
export let curColor = "#409eff";
// 动态切换主题色
export function changeThemeColor(newColor) {
const options = {
newColors: [...forElementUI.getElementUISeries(newColor)]
};
return client.changer.changeColor(options, Promise).then(t => {
curColor = newColor;
localStorage.setItem("theme_color", curColor);
});
}
export function initThemeColor() {
const savedColor = localStorage.getItem("theme_color");
if (savedColor) {
curColor = savedColor;
changeThemeColor(savedColor);
}
}
四、组件中使用
<el-color-picker v-model="mainColor" size="small" @change="changeColor"></el-color-picker>
<script>
import Vue from "vue";
import { ColorPicker } from "element-ui";
import { changeThemeColor, curColor } from "./utils/thems.js";
Vue.use(ColorPicker);
export default {
name: "App",
data() {
return {
mainColor: curColor
};
},
methods: {
changeColor(newColor) {
changeThemeColor(newColor).then(t => {
console.log("t: ", t);
});
}
}
};
</script>
五、项目加载时,使用上次修改后的主题色
//main.js
import { initThemeColor } from './utils/theme.js'
initThemeColor()