·
0 min read

Vue Tip: Avoid Empty Class Attributes

Vue Tip: Avoid Empty Class Attributes Image

If you want to conditionally add a class to an element in Vue, you might be tempted to use a ternary operator to check if a condition is met.

However, this can lead to an empty class attribute being rendered when the condition is false:

Component.vue
<template> <div :class="isDisabled ? 'disabled' : null"></div> <!-- Will render <div class></div> --> </template>

Instead, use a falsy value like an empty string to avoid this issue:

Component.vue
<template> <div :class="isDisabled ? 'disabled' : ''"></div> <!-- Will render <div></div> --> </template>

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:

I will never share any of your personal data. You can unsubscribe at any time.