antd-design-vue动态自定义主题色

·  阅读 158
  1. 安装依赖(注意版本号)
"devDependencies": {
    "less": "^2.7.2",
    "less-loader": "^5.0.0",
    "antd-theme-generator": "^1.2.5"
  },
复制代码

2.项目根目录创建theme.js文件

const path = require("path");
const { generateTheme } = require("antd-theme-generator");
const options = {
  antDir: path.join(__dirname, "./node_modules/ant-design-vue"), // antdv对应具体位置
  stylesDir: path.join(__dirname, "./src/assets/styles/theme"), // less文件夹对应具体位置
  varFile: path.join(__dirname, "./src/assets/styles/theme/variables.less"), // 文件夹变量对应具体位置
  mainLessFile: path.join(__dirname, "./src/assets/styles/theme/index.less"),
  themeVariables: [ // 指定所有我们自定义需要切换的样式变量
    "@primary-color",
    "@link-color",
    "@border-color-base",
  ],
  indexFileName: "./public/index.html",
  outputFilePath: path.join(__dirname, "./public/theme.less"), // 打包出来的文件
};
generateTheme(options)
  .then((less) => {
    console.log("Theme generated successfully");
  })
  .catch((error) => {
    console.log("Error", error);
  });
复制代码
  1. 修改vue.config.js
require("./theme.js");
module.exports = {
    css: {
            loaderOptions: {
            less: {
                lessOptions: {
                    modifyVars: {},
                    javascriptEnabled: true,
                },
            },
        },
    },
}
复制代码
  1. 创建自定义主题文件src/assets/style/variables.less
@import "~ant-design-vue/lib/style/themes/default.less";
@primary-color: #1890ff; // 全局主色
@link-color: #1890ff; // 链接色
@border-color-base: #d9d9d9; // 边框色

:root {
  --primary-color: @primary-color;
  --link-color: @link-color;
  --border-color-base: @border-color-base;
}
复制代码
  1. 修改public/index.html文件
<!DOCTYPE html>
<html lang="">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <link rel="icon" href="<%= BASE_URL %>favicon.ico">
  <title>
    <%= htmlWebpackPlugin.options.title %>
  </title>
</head>

<body>
  <noscript>
    <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
        Please enable it to continue.</strong>
  </noscript>
  <div id="app"></div>
  <!-- built files will be auto injected -->
  <link rel="stylesheet/less" type="text/css" href="./theme.less" />
  <script>
    window.less = {
      async: false,
      env: 'production'
    };
  </script>
  <script type="text/javascript" src="./less.min.js"></script>
</body>

</html>
复制代码

6.动态自定义颜色

window.less.modifyVars({
    "@primary-color": '#f5222d',
})
复制代码
color: var(--link-color); // 不能直接使用less变量,因为编译时已经被转换为对应值,导致无法实时切换主题色效果
复制代码
分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改