提示 antd 只能用less
1.插件安装
npm install @zougt/vite-plugin-theme-preprocessor -D
2.vite.config.ts 代码
import vue from '@vitejs/plugin-vue'
import { defineConfig } from "vite";
import path from "path";
import themePreprocessorPlugin from "@zougt/vite-plugin-theme-preprocessor";//换肤插件
export default defineConfig({
plugins: [
// 引入插件
vue(),
themePreprocessorPlugin({
// 使用Less
less: {
// 此处配置自己的主题文件
multipleScopeVars: [
{
scopeName: "theme-default",
path: path.resolve("src/style/theme/default.less"),
},
{
scopeName: "theme-green",
path: path.resolve("src/style/theme/index.less"),
},
],
defaultScopeName: "theme-default", // 默认取 multipleScopeVars[0].scopeName
extract: false,// 在生产模式是否抽取独立的主题css文件
},
}),
]
})
3.创建目录
在src/style/theme 创建你需要切换主题less文件,目录地址可更改
//default.less 修改其他的类名 可在官方文档查找 其他主题less文件一样
// 引入官方主题
@import 'ant-design-vue/dist/antd.less';
// 修改组件库主题
@primary-color: red;
// 自定义变量
@custom-color: #000000;
4.ts
<script setup lang="ts">
import { ref } from 'vue'
import { toggleTheme } from "@zougt/vite-plugin-theme-preprocessor/dist/browser-utils.js";
const checked = ref<boolean>(false);
// 切换主题回调
const change = (value: boolean) => {
// 如果开关打开,就切换为绿色主题,否则默认黄色主题
let html=document.querySelector("html");
if (value) {
toggleTheme({
scopeName: "theme-green",
});
html.setAttribute("class", "theme-green")
console.log("已切换为绿色主题");
} else {
toggleTheme({
scopeName: "theme-default",
});
html.setAttribute("class", "theme-default")
console.log()
console.log("已切换为默认主题");
}
};
</script>
<template>
<a-button type="primary">Primary Button</a-button>
<a-button>Default Button</a-button>
<a-button type="primary" @click="change(true)">Dashed Button</a-button>
<a-button type="primary" @click="change(false)">Text Button</a-button>
</template>
<style scoped lang="less"></style>//style 一定要加less 不然不会生效
,