【问题标题】:Tailwind: modify classes dynamically for Vue appTailwind:为 Vue 应用动态修改类
【发布时间】:2021-10-23 22:46:54
【问题描述】:

我有一个在 tailwind.config.js 中配置 Tailwinds 的 Vue3 应用程序

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

例如:


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>

【问题讨论】:

  • 请分享一个您想要实现的示例
  • @BoussadjraBrahim 我添加了示例
  • 你想要像主题化你的应用吗?
  • 我需要根据配置文件动态更改某些元素的基色。如果这可以通过主题来完成,那么可以,但我不知道
  • 按照你的做法是不可能的,但你可以以不同的方式实现主题化过程

标签: css vue.js tailwind-css


【解决方案1】:

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

@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 添加类theme-1 到根元素,例如:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2022-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 2021-02-17
    • 2021-06-05
    • 2020-09-25
    相关资源
    最近更新 更多