Search code examples
vuejs3tailwind-cssvitetailwind-in-js

How to use dynamic class of tailwindcss like this in project of vue3 and vite?


<script>
export default {
  name: "TestTailwind",
};
</script>
<script setup></script>

<template>
  <div class="">
    <div v-for="i in 20" :key="i" :class="[`m-${i}`]">m-{{ i }}</div>
    <div v-for="i in 20" :key="i" :class="[`p-${i}`]">p-{{ i }}</div>

  </div>
</template>

<style lang="scss" scoped>
</style>

I try to use dynamic class , but tailwind not give me the class right.

enter image description here

Expect:

enter image description here


Solution

  • It's because of tailwind tree shaking. You need to add the classes you want to generate dynamically to the safelist in your tailwind.config file because tailwind can't detect used classes with this dinamic syntax.

    Here is the code:

    module.exports = {
      content: [
        './pages/**/*.{html,js}',
        './components/**/*.{html,js}',
      ],
      safelist: [
        'p-1',
        'p-2',
        'p-3',
        // ...
      ],
      // ...
    }
    

    You can read the docs here