DEV Community

Cover image for Vue + Tailwind and Dynamic Classes
Andrew Bell
Andrew Bell

Posted on

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'
          },
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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'
    ]
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
alexanderop profile image
Alexander Opalic

Nice tip I remember that I faced this kind of issue also once at work