Maison >interface Web >js tutoriel >Vue Tailwind et classes dynamiques

Vue Tailwind et classes dynamiques

Mary-Kate Olsen
Mary-Kate Olsenoriginal
2024-10-08 16:23:30570parcourir

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.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn