·
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
1<script setup lang="ts">
2interface Props {
3  isDisabled?: boolean
4  error?: unknown
5}
6const props = defineProps<Props>()
7
8const disabledClasses = computed(() => props.isDisabled ? 'cursor-not-allowed' : '')
9const errorClasses = computed(() => props.error ? 'text-danger' : '')
10</script>
11
12<template>
13  <div class="border p-4" :class="[errorClasses, disabledClasses]">
14    <slot />
15  </div>
16</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
1<template>
2  <div class="border p-4" :class="[isDisabled ? disabledClasses : '', errorClasses]">
3    <slot />
4  </div>
5</template>

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

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