One data grid for JavaScript, React, Vue & Angular. Sorting, filtering, virtualization, pinning, and CSV export included. Early access $199 $349 → [Get it now]

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.
How to create a single page application using React.js
How to create a single page application using React.js

React v18.0 – finally is of legal age?
React v18.0 – finally is of legal age?

Quo Vadis Vue.js
Quo Vadis Vue.js

Vue UI component libraries 2022
Vue UI component libraries 2022