首頁 >web前端 >js教程 >Vue Tailwind 和動態類

Vue Tailwind 和動態類

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-08 16:23:30570瀏覽

Vue + Tailwind and Dynamic Classes

A project I've been working on recently makes use of Vite, Vue and Tailwind.

After some time working with custom colors, I faced some confusion.

Adding and using the custom colors in a template, was not the issue - the process is made very clear using the Tailwind Documentation

// tailwind.config.js
module.exports = {
    theme: {
        colors: {
          'custom-green': {
              50: '#9bd1b2',
              ...
              700: '#284735'
          },
        }
    }
}

My issue was when using the custom colors with dynamic and static css classes in the Vue template.

When running the project with npm run dev or vite the bg-custom-green-50 or text-custom-green-50 did not work and never appeared in the css files.

My understanding is if your full css class name does not exist in the template then tailwind will not add it or generate it in the css file.

Assuming the css classes: text-custom-green-50 or bg-custom-green-50 are not used anywhere else in the project

The example below will not work

<template>
    <h3 :class="['font-bold', colorClass]">{{ heading }}</h3>
</template>
<script type="text/javascript">
    const colorClass = ref('')

    // color being set somewhere else in the component logic
    colorClass.value = 'text-custom-green-50'
</script>

The example below will work

<template>
    <h3 :class="['font-bold', colorClass]">{{ heading }}</h3>
    <p class="text-custom-green">Green text</p>
</template>
<script type="text/javascript">
    const colorClass = ref('')

    // color being set somewhere else in the component logic
    colorClass.value = 'text-custom-green-50'
</script>

The difference between the two examples is the text-custom-green css class is added to the template so tailwind will add it to the generated css file.

To overcome this you can add any custom colors or tailwind classes to a safelist within your tailwind.config.js file.

// tailwind.config.js
module.exports = {
    safelist: [
        'text-custom-green-50',
        'bg-custom-green-50'
    ]
}

These colors will be available even if they are not used directly in a template, but added dynamically at another point

Hopefully someone else finds this helpful.

以上是Vue Tailwind 和動態類的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn