在可重用的 VueJS 组件中覆盖 Tailwind CSS 类

Mos*_*she 10 vue.js vue-component vuejs2 tailwind-css

我使用 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>
Run Code Online (Sandbox Code Playgroud)

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

// index.vue

<Button></Button>
<Button class="bg-red-600"></Button>
<Button class="bg-blue-600"></Button>
Run Code Online (Sandbox Code Playgroud)

问题是这只能起到一半的作用。也就是说,bg-blue-600确实覆盖了bg-green-500我在Button.vue. 但bg-red-600不能忽略的背景颜色(presumbably,因为bg-red-600来之前在CSS源代码。

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

谢谢。

小智 0

作为解决方法,您可以使用 props:

<!-- 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>
Run Code Online (Sandbox Code Playgroud)
<!-- index.vue -->
<Button background="bg-red-600"></Button>
<Button background="bg-blue-600"></Button>
Run Code Online (Sandbox Code Playgroud)