[Vuejs]-Dynamic class not rendering in browser tailwind – Vue

0👍

@JHeth Thanks for the comment

Although there are many ways of solving the above, I came up with a CSS solution by adding styles to the generated classes in style block.

 <script>
    export default {
      name: "MyComponent",
    
      functional: true,
    
      props: {
        variant: {
          type: String,
          required: true,
        },
      },
    
      render(createElement, { children, props, data }) {
        const attrs = {
          staticClass: `bg-demo-${props.variant}`,
        };
    
        return createElement("div", attrs, children);
      },
    };
</script>
<style>
 .bg-demo-success {
    background-color: var(--success-color);
 }
</style>

0👍

Is it recommended to use dynamic class in tailwind ?

No

Using dynamic classes in tailwind-css is usually not recommended because tailwind uses tree-shaking i.e any class that wasn’t declared in your source files, won’t be generated in the output file.

Hence it is always recommended to use full class names

According to Docs

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

Isn’t there work around ?

Yes

As a last resort, Tailwind offers Safelisting classes.

Safelisting is a last-resort, and should only be used in situations where it’s impossible to scan certain content for class names. These situations are rare, and you should almost never need this feature.

In your example,you want to have 100 500 700 shades of colors. You can use regular expressions to include all the colors you want using pattern and specify the shades accordingly .

Note: You can force Tailwind to create variants as well:

In tailwind.config.js

module.exports = {
  content: [
    './pages/**/*.{html,js}',
    './components/**/*.{html,js}',
  ],
  safelist: [
    {
      pattern: /bg-(red|green|blue|orange)-(100|500|700)/, // You can display all the colors that you need
      variants: ['lg', 'hover', 'focus', 'lg:hover'],      // Optional
    },
  ],
  // ...
}

Leave a comment