Tailwind:为 Vue 应用程序动态修改 类

Tailwind: modify classes dynamically for Vue app

我有一个在 tailwind.config.js

中配置了 Tailwinds 的 Vue3 应用程序

是否可以从 tailwind.config.js 动态更改预配置 class 的值?

例如:


tailwind.config.js:

const defaultTheme = require("tailwindcss/defaultTheme");

module.exports = {
  purge: ["./index.html", "./src/**/*.{vue,js,ts,jsx,tsx}"],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {
      colors: {
        base: {
          DEFAULT: "#6e0147",
        },
      },
      fontFamily: {
        sans: ["Interstate", "Inter var", ...defaultTheme.fontFamily.sans],
      },
    },
  },
  variants: {
    extend: {
      ringWidth: ["hover", "active"],
      ringColor: ["hover", "active"],
      ringOpacity: ["hover", "active"],
      ringOffsetWidth: ["hover", "active"],
      ringOffsetColor: ["hover", "active"],
    },
  },
  plugins: [],
};

VueComponent.vue :

<template>
   <div class="text-base">text here</div>
</template>

<script>
   export default {
      .....

      mounted(){
         tailwind.config.colors.base = "#00000" // change tailwind color of class somehow
      }
   }
</script>

在您的 tailwind.css 中添加一个名为 --text-color-base 的 CSS 变量(您可以添加多个),在基本主题中以及 theme-1:

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base{
  :root{
    --text-color-base:#6e0147;
  }

    .theme-1{
       --text-color-base:#000000;
     }
}

tailwind.config.js 中使用皮肤键扩展主题选项中的 textColor 字段,它将包含用于您的文本颜色的不同变量:

theme: {
    extend: {
      textColor:{
           skin:{
              base:"var(--text-color-base)"
            }
        },
      colors: {
        base: {
          DEFAULT: "#6e0147",
        },
      },
      fontFamily: {
        sans: ["Interstate", "Inter var", ...defaultTheme.fontFamily.sans],
      },
    },

然后您可以像 class="text-skin-base" 一样使用它,以应用 theme-1 将 class theme-1 添加到根元素,例如 :

<div class="theme-1">
    <h1 class="text-skin-base">text here</h1>
    ...
</div>

然后在您的脚本中,您可以将根 class 绑定到 属性 并在脚本中更新:

<div :class="myTheme">
    <h1 class="text-skin-base">text here</h1>
    ...
</div>

<script>
   export default {
      .....
      data(){
        return{
          myTheme:''
        } 
       },
      mounted(){
         this.myTheme="theme-1"
      }
   }
</script>