vite2 antD 动态切换主题

提示 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  不然不会生效

,

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值