less方案实现主题切换 window.less.modifyVars

UI框架版本:“ant-design-vue”: “^1.7.6”,
以下通过less切换UI库样式颜色变量来切换主题

实现步骤 (以下代码去掉了多余部分)

1.下载依赖(我是指定了版本,如果你愿意自己踩坑也可以不指定,直接下载最高版本)

"dependencies": {
    
    
    "antd-theme-generator": "1.1.6",
    "antd-theme-webpack-plugin": "1.2.0",
}

2.配置 vue.config.js

const path = require('path')
const AntDesignThemePlugin = require("antd-theme-webpack-plugin");

const options = {
    
    
  antDir: path.join(__dirname, "./node_modules/ant-design-vue"), //antd包位置
  stylesDir: path.join(__dirname, "./src/styles/theme"), //主题文件所在文件夹
  varFile: path.join(__dirname, "./src/styles/theme/variables.less"), // 自定义默认的主题色
  mainLessFile: path.join(__dirname, "./src/styles/theme/index.less"), // 项目中其他自定义的样式(如果不需要动态修改其他样式,该文件可以为空)
  outputFilePath: path.join(__dirname, "./public/color.less"), //提取的less文件输出到什么地方
  themeVariables: ["@primary-color", "@link-color", "@border-color-base", "@text-color", "@border-radius-base", "@font-size-base"], //要改变的主题变量
  indexFileName: "./public/index.html", // index.html所在位置
  generateOnce: false // 是否只生成一次(if you don't want to generate color.less on each chnage in code to make build process fast in development mode, assign it true value. But if you have new changes in your styles, you need to re-run your build process npm start.)
};

module.exports {
    
    
	configureWebpack: {
    
    
    // webpack plugins
    plugins: [
      // 引入依赖配置
      new AntDesignThemePlugin(options)
    ],
  },
  css: {
    
    
    loaderOptions: {
    
    
      less: {
    
    
      	// 设置默认主题
        modifyVars: {
    
    
          // less vars,customize ant design theme
          // 'primary-color': '#FF824D',
          // // 'link-color': '#F5222D',
          // 'border-radius-base': '2px',
          // 'layout-header-height': '50px'
        },
        // DO NOT REMOVE THIS LINE
        javascriptEnabled: true
      }
    }
  },
}

3.在src文件夹下创建文件夹路径和文件

src> styles>theme>index.less
src> styles>theme>variables.less

index.less 为空文件
variables.less 引入一个路径

@import "~ant-design-vue/lib/style/themes/default.less";

4.配置index.html

<link rel="stylesheet/less" type="text/css" href="./color.less" />
<script>
  window.less = {
    
    
    async: false,
    env: 'development'//production  development
  };
</script>
<script src="https://cdn.bootcss.com/less.js/2.7.3/less.min.js"></script>

上面所引用的 ./color.less 和index.html一样同在public文件夹下,是前面下载的依赖配置后,启动项目 自动生成的

5.切换主题

methods: {
    
    
	// 通过点击切换主题的按钮触发此事件
    checkTheme(data) {
    
    
      console.log('window.less:', window.less)
      window.less.modifyVars({
    
    
        // "@primary-color": '#E60012',
        "@link-color": '#E60012', // 控制组件主题颜色
        // "@border-color-base": '#000000',
        // "@text-color": '#000000',
        // "@border-radius-base": '10px',
        // "@font-size-base": '30px'
      });
    }
  },

猜你喜欢

转载自blog.csdn.net/weixin_34403976/article/details/125558503