简体   繁体   中英

Tailwind: modify classes dynamically for Vue app

I have a Vue3 application with Tailwinds configured in tailwind.config.js

Is it possible to dynamically change the value of a preconfigured class from tailwind.config.js?

For example:


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>

In your tailwind.css add a CSS variable called --text-color-base (you could add multiple) in the base theme and also in theme-1 :

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

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

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

in tailwind.config.js extend the textColor field in the theme option with skin key which will contain the different variable for your text color:

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

then you could use it like class="text-skin-base" , to apply the theme-1 add the class theme-1 to the root element like:

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

then in your script you could bind the root class to a property and you update in the script:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM