1,引入依赖:
npm i webpack-theme-color-replacer
2,新建一个webpack插件的js :webpack_theme_plugin.js
const ThemeColorReplacer = require("webpack-theme-color-replacer");
const generate = require("@ant-design/colors/lib/generate").default;
const getAntdSerials = color => {// 淡化(即less的tint)const lightens = new Array(9).fill().map((t, i) => {return ThemeColorReplacer.varyColor.lighten(color, i / 10);});const colorPalettes = generate(color);const rgb = ThemeColorReplacer.varyColor.toNum3(color.replace("#", "")).join(",");return lightens.concat(colorPalettes).concat(rgb);
};
const themePluginOption = {fileName: "css/theme-colors-[contenthash:8].css",matchColors: getAntdSerials("#1890ff"), // 主色系列// 改变样式选择器,解决样式覆盖问题changeSelector(selector) {return selector;}
};const createThemeColorReplacerPlugin = () =>new ThemeColorReplacer(themePluginOption);module.exports = createThemeColorReplacerPlugin;
3,在vue.config.js中使用
const ThemeColorReplacerPlugin = require("./webpack_plugins/webpack_theme_plugin");configureWebpack: {plugins: [ThemeColorReplacerPlugin(),new CompressionPlugin({filename: "[path].gz[query]",algorithm: "gzip",test: productionGzipExtensions,// 只处理大于xx字节 的文件,默认:0threshold: 10240,// 示例:一个1024b大小的文件,压缩后大小为768b,minRatio : 0.75minRatio: 0.8, // 默认: 0.8// 是否删除源文件,默认: falsedeleteOriginalAssets: false})]}
4,创建改变主题方法 :themeColor.js
import client from "webpack-theme-color-replacer/client";
import generate from "@ant-design/colors/lib/generate";export default {getAntdSerials(color) {// 淡化(即less的tint)const lightens = new Array(9).fill().map((t, i) => {return client.varyColor.lighten(color, i / 10);});// colorPalette变换得到颜色值const colorPalettes = generate(color);// const rgb = client.varyColor.toNum3(color.replace('#', '')).join(',')console.log(lightens.concat(colorPalettes).concat(color));return lightens.concat(colorPalettes).concat(color);},changeColor(newColor) {var options = {newColors: this.getAntdSerials(newColor), // new colors array, one-to-one corresponde with `matchColors`changeUrl(cssUrl) {return `/${cssUrl}`; // while router is not `hash` mode, it needs absolute path}};return client.changer.changeColor(options, Promise);}
};
5,使用:
import themeColor from "../plugins/themeColor";methods: {//改变颜色changeColor(color) {themeColor.changeColor(color).then(res => {console.log(res);});},
}