JAVASCRIPT

Dynamically Apply Multiple CSS Classes and Inline Styles in Vue 3

Learn to dynamically bind multiple CSS classes using objects and arrays, and inline styles with objects in Vue 3 components for reactive, data-driven UI.

// App.vue
<template>
  <div :class="computedClasses" :style="computedStyles">
    This text changes style and class dynamically.
  </div>
  <button @click="toggleActive">Toggle Active</button>
  <button @click="toggleError">Toggle Error</button>
  <button @click="changeFontSize">Change Font Size</button>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';

const isActive = ref(true);
const hasError = ref(false);
const fontSize = ref(16);

const computedClasses = computed(() => ({
  'active-class': isActive.value,
  'text-danger': hasError.value,
  'another-class': true
}));

const computedStyles = computed(() => ({
  fontSize: `${fontSize.value}px`,
  color: isActive.value ? 'blue' : 'grey',
  backgroundColor: hasError.value ? '#ffebee' : '#e0f7fa'
}));

function toggleActive() {
  isActive.value = !isActive.value;
}

function toggleError() {
  hasError.value = !hasError.value;
}

function changeFontSize() {
  fontSize.value = fontSize.value === 16 ? 24 : 16;
}
</script>

<style scoped>
.active-class {
  border: 2px solid blue;
  padding: 10px;
}
.text-danger {
  color: red !important; /* using !important for demonstration */
  font-weight: bold;
}
.another-class {
  margin-top: 10px;
}
</style>
How it works: This snippet demonstrates how to apply multiple CSS classes and inline styles dynamically in Vue 3. Using `:class` with an object allows classes to be toggled based on reactive state (e.g., `isActive.value`, `hasError.value`). An array can also be used for static and dynamic classes. Similarly, `:style` with an object binds inline CSS properties, which can also be reactive. Computed properties are leveraged to combine multiple conditions and states into dynamic class and style objects, ensuring the UI updates automatically.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs