·
1 min read

Vue Tip: How I Write Class & Style Bindings

Vue Tip: How I Write Class & Style Bindings Image

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:

Component.vue
<script setup lang="ts"> interface Props { isDisabled?: boolean error?: unknown } const props = defineProps<Props>() const disabledClasses = computed(() => props.isDisabled ? 'cursor-not-allowed' : '') const errorClasses = computed(() => props.error ? 'text-danger' : '') </script> <template> <div class="border p-4" :class="[errorClasses, disabledClasses]"> <slot /> </div> </template>

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:

Component.vue
<template> <div class="border p-4" :class="[isDisabled ? disabledClasses : '', errorClasses]"> <slot /> </div> </template>

Alternatively, you can use the object syntax to apply classes based on a condition:

Component.vue
<template> <div class="border p-4" :class="[{ disabledClasses: isDisabled }, errorClasses]"> <slot /> </div> </template>