We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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:
<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:
<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:
<template>
<div class="border p-4" :class="[{ disabledClasses: isDisabled }, errorClasses]">
<slot />
</div>
</template>
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.