Programmatically craft Tailwind classes with Vue

1.4k views Asked by At

I Just want to have dynamic tailwind classes values that changes when change a data value, it is possible to do it using tailwind?

In my example I have a double side menus and a main content, I want to set the menus width and programmatically change the margins that have the main content.

I don't know why but tailwind doesn't apply my crafted classes even if in the browser shows the right class in the div element.


Left side menu:

(right is equal)

<nav
   class="fixed overflow-x-scroll bg-gray-700 top-16 h-screen"
   :class="classes.leftSidebar"
   >
   <h1 class="text-xl text-center font-bold pt-5">Menu</h1>
   <ul class="list-none text-white text-center">
      <li class="my-8">
         <a href="#">Teams</a>
      </li>
      <li class="my-8">
         <a href="#">Projects</a>
      </li>
      <li class="my-8">
         <a href="#">Favourites</a>
      </li>
      <li class="my-8">
         <a href="#">Notifications</a>
      </li>
      <li class="my-8">
         <a href="#">Members</a>
      </li>
   </ul>
</nav>

Content:

<main :class="classes.main">
    <slot></slot>
</main>

Script:

data() {
        return {
            showingNavigationDropdown: false,
            sidebar_left_w: 64,
            sidebar_right_w: 64,
        }
    },

    computed: {
        classes() {
            return {
                leftSidebar: `w-[${this.sidebar_left_w}rem]`,
                rightSidebar: `w-[${this.sidebar_right_w}rem]`,
                main: [`mr-[${this.sidebar_right_w}rem]`, `ml-[${this.sidebar_left_w}rem]`],
            }
        }
    },

I also tried leftSidebar: `w-${this.sidebar_left_w}`, but same results

1

There are 1 answers

1
tauzN On BEST ANSWER

This is not possible with Tailwind CSS

The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete unbroken strings in your source files.

If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS:

Don't construct class names dynamically

<div class="text-{{ error ? 'red' : 'green' }}-600"></div>
<!-- This will not work -->

In the example above, the strings text-red-600 and text-green-600 do not exist, so Tailwind will not generate those classes.

Instead, make sure any class names you’re using exist in full:

Always use complete class names

<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>

As long as you always use complete class names in your code, Tailwind will generate all of your CSS perfectly every time.

source