Styling your components in Vue.js can be done in multiple ways. One of the most common ways is to use the class
attribute, especially if you are using a CSS framework like Tailwind. In combination with v-bind
you can dynamically assign classes to your components. The same goes for the style
attribute, which allows you to apply inline styles to your components.
I prefer the combination of the class attribute in combination with :class
to apply a list of classes as an array:
The class
attribute is an array of classes that should always be applied to the element. The classes bound via :class
are computed properties that are dynamically evaluated and added to the element. This way, I can easily distinguish between classes that should always be applied and classes that are conditionally applied.
You can also toggle a class inside the list of classes based on a condition:
Alternatively, you can use the object syntax to apply classes based on a condition:
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: When You Should Use a Composable
Vue composables are a way to encapsulate logic in a reusable way in Vue 3. They are a great way to share logic between components, but I often see them used in places where they are not needed.
Nuxt Tip: Run Code Once During SSR or CSR
Since Nuxt 3.9 you can use the useOnce composable to run a given function or block of code once during server-side rendering or client-side navigation.