【问题标题】:Overriding Tailwind CSS Classes in a Reusable VueJS Component在可重用的 VueJS 组件中覆盖 Tailwind CSS 类
【发布时间】:2020-10-13 04:58:33
【问题描述】:

我使用 TailwindCSS 创建了一个 VueJS 按钮组件。我的目标是为该按钮组件提供一些基本样式(使用 tailwindcss 类),并在需要时选择覆盖它们(再次,使用 tailwind css 类)。

例如,这里是Button 组件的简化版本:

// Button.vue

<template>
  <button class="bg-green-500 text-white py-2 px-4 rounded">
    Click Me
  </button>
</template>

这是我在另一个文件中使用该组件的示例:

// index.vue

<Button></Button>
<Button class="bg-red-600"></Button>
<Button class="bg-blue-600"></Button>

问题是这只是成功的一半。也就是说,bg-blue-600 确实覆盖了我在Button.vue 中设置为默认值的bg-green-500。但是bg-red-600确实覆盖背景颜色(大概是因为bg-red-600在css源代码中出现得更早。

因此,我想知道如何正确设置它?也就是说,我怎样才能给Button 组件一些基本样式(同样,使用tailwind css 类),同时还提供使用tailwind css 类覆盖这些样式的选项。

谢谢。

【问题讨论】:

    标签: vue.js vuejs2 vue-component tailwind-css


    【解决方案1】:

    作为一种解决方法,您可以使用道具:

    <!-- Button.vue -->
    <template>
      <button :class="background + ' text-white py-2 px-4 rounded'">
        Click Me
      </button>
    </template>
    
    <script>
    export default {
      props: {
        background: {
          type: String,
          default: "bg-green-500",
        },
      },
    };
    </script>
    
    <!-- index.vue -->
    <Button background="bg-red-600"></Button>
    <Button background="bg-blue-600"></Button>
    

    【讨论】:

      【解决方案2】:

      这是因为Button 上的组件属性class 不会与html button 挂钩。为此,只需像这样将属性绑定到孩子

      <button v-bind="$attrs"...>
      

      这将使您在 Button 上指定的所有属性(不是道具)绑定到 html 按钮。

      话虽如此,我个人更喜欢使用 @apply 指令创建一个按钮类并在我的项目中重用它。

      【讨论】:

      • 在 vue2 中,这个问题被标记为 class 确实是 trickle down,所以我认为你的回答具有误导性
      【解决方案3】:

      您可以在组件的作用域样式内使用 Tailwinds @apply,它将被覆盖。

      【讨论】:

      • 你能分享一些示例代码吗?我尝试添加但仍然没有效果
      【解决方案4】:

      如果您使用 @apply 指令创建顺风类,您可以添加 !important 以使其在使用时覆盖其他颜色类。

      您需要使用 lang="postcss" 属性才能在组件中使用 tailwind 指令。

      <style lang="postcss">
      .my-overriding-class{
          @apply bg-red-600 !important 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-08-19
        • 2018-05-28
        • 1970-01-01
        • 2019-09-27
        • 1970-01-01
        • 2019-11-30
        • 1970-01-01
        相关资源
        最近更新 更多