Beginner LevelVue JS
What are the different ways to bind CSS classes and inline styles in Vue?
❓ Interview Prompt: Explain dynamic class and style bindings using object syntax, array syntax, and component merging.
Vue extends ':class' and ':style' attribute bindings to support objects and arrays alongside standard strings.
1. Object Syntax:
•
Class: ':class="{ active: isActive, "text-danger": hasError }"' toggles class names based on truthy values.
•
Style: ':style="{ color: activeColor, fontSize: fontSize + "px" }"' applies camelCase inline CSS properties.
2. Array Syntax:
•
Pass an array of class names: ':class="[activeClass, errorClass]"'. Can combine objects inside arrays: ':class="[baseClass, { active: isActive }]"'!
Code Implementation Example
html
<script setup>
import { ref } from 'vue';
const isActive = ref(true);
const hasError = ref(false);
const textColor = ref('red');
const fontSize = ref(16);
</script>
<template>
<!-- 1. Object Class Binding -->
<div :class="{ active: isActive, error: hasError }">Status Card</div>
<!-- 2. Inline Style Binding -->
<p :style="{ color: textColor, fontSize: fontSize + 'px' }">Dynamic Styled Text</p>
</template>💡Dynamic CSS class and inline style bindings using object maps.
🎯 Interview Key Takeaway
Bind :class and :style using object or array maps to toggle CSS styles dynamically based on reactive state.
#class#style#CSS#Beginner
Back to all Vue JS Questions→