JAVASCRIPT

Advanced Dynamic Class and Style Binding in Vue 3

Master dynamic class and style binding in Vue 3 using object and array syntax with reactive data and computed properties for complex UI states.

// DynamicStyling.vue
<template>
  <div id="app">
    <h1>Dynamic Styling Demo</h1>

    <h2>Dynamic Class Binding</h2>
    <div :class="{ active: isActive, 'text-red': hasError }">
      <p>Object Syntax: Conditionally active and red text.</p>
    </div>

    <div :class="[primaryClass, { 'large-text': isLarge }"]">
      <p>Array Syntax: Always primary, conditionally large.</p>
    </div>

    <div :class="computedClasses">
      <p>Computed Property: Classes based on complex logic.</p>
    </div>

    <button @click="toggleActive">Toggle Active</button>
    <button @click="toggleError">Toggle Error</button>
    <button @click="toggleLarge">Toggle Large</button>

    <h2>Dynamic Style Binding</h2>
    <div :style="{ backgroundColor: bgColor, fontSize: fontSize + 'px', border: borderStyle }">
      <p>Object Syntax: Background, font size, border.</p>
    </div>

    <div :style="computedStyles">
      <p>Computed Property: Styles based on conditions.</p>
    </div>

    <button @click="changeBgColor">Change Background</button>
    <input type="range" v-model="fontSize" min="10" max="40" />
  </div>
</template>

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

// Reactive data for class binding
const isActive = ref(false);
const hasError = ref(false);
const isLarge = ref(true);
const primaryClass = 'primary-item';

const toggleActive = () => { isActive.value = !isActive.value; };
const toggleError = () => { hasError.value = !hasError.value; };
const toggleLarge = () => { isLarge.value = !isLarge.value; };

// Computed property for complex class logic
const computedClasses = computed(() => {
  return {
    'highlight-background': isActive.value && !hasError.value,
    'warning-border': hasError.value,
    'text-bold': isLarge.value || isActive.value
  };
});

// Reactive data for style binding
const bgColor = ref('#f0f0f0');
const fontSize = ref(16);
const borderStyle = ref('1px solid #ccc');

const changeBgColor = () => {
  bgColor.value = bgColor.value === '#f0f0f0' ? '#e6ffe6' : '#f0f0f0';
};

// Computed property for complex style logic
const computedStyles = computed(() => {
  const baseStyles = {
    padding: '15px',
    borderRadius: '5px',
  };
  if (isActive.value) {
    baseStyles.boxShadow = '0 0 8px rgba(0, 123, 255, 0.5)';
  }
  if (hasError.value) {
    baseStyles.backgroundColor = '#ffe0e0';
    baseStyles.color = 'red';
  }
  return baseStyles;
});
</script>

<style>
#app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; }
div[class*="text-"] { margin-bottom: 10px; padding: 10px; border: 1px solid #eee; }
.active { background-color: #e0f7fa; border-color: #00bcd4; }
.text-red { color: red; }
.primary-item { border-left: 5px solid blue; padding-left: 10px; }
.large-text { font-size: 20px; font-weight: bold; }
.highlight-background { background-color: #d1ecf1; }
.warning-border { border-color: orange; }
.text-bold { font-weight: bold; }
button { margin: 5px; padding: 8px 15px; }
</style>
How it works: This snippet showcases the flexible ways to dynamically bind CSS classes and inline styles in Vue 3. It covers object syntax for conditional classes (`:class="{ classA: condition }"`), array syntax for combining multiple classes (`:class="[staticClass, { dynamicClass: condition }]"`), and the power of computed properties for deriving classes based on complex reactive logic. Similarly, it demonstrates dynamic inline style binding using object syntax (`:style="{ property: value }"`) and with computed properties, allowing for highly interactive and responsive UI styling.

Need help integrating this into your project?

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

Hire DigitalCodeLabs