How to use conditional classes in Vue

Conditional classes in Vue enable dynamic styling that responds to component state, creating interactive interfaces where styling changes based on data and events. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented conditional classes in thousands of Vue components for dynamic theming and state-based styling. From my expertise, the most effective approach is using object syntax for simple conditions and computed properties for complex logic. This method provides reactive styling that automatically updates when component state changes.

Use :class with object syntax where keys are class names and values are boolean expressions.

<template>
  <div :class="{ active: isActive, disabled: isDisabled }">
    Dynamic Button
  </div>
</template>

<script setup>
import { ref } from 'vue'

const isActive = ref(true)
const isDisabled = ref(false)
</script>

The :class directive accepts objects where keys are CSS class names and values are boolean expressions that determine whether the class is applied. When isActive is true, the ‘active’ class is added to the element. Multiple conditions can be combined in a single object.

Best Practice Note:

This is the same conditional class approach we use in CoreUI Vue components for dynamic styling. Use computed properties for complex class logic and maintain consistent naming conventions for better maintainability.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team