Class & Style Bindings
Vue extends class and style bindings, allowing you to pass objects or arrays to dynamically apply styles based on component state.
1 Object and Array Syntax
Applying classes and styles dynamically can be written in two ways:
- Class Object Syntax: Applies classes dynamically based on boolean flags:
:class="{ active: isActive, 'text-error': hasError }". - Class Array Syntax: Applies a list of class strings dynamically:
:class="[baseClass, activeClass]". - Inline Styles Binding: Binds JavaScript objects to the style attribute, camelCasing property names:
:style="{ color: activeColor, fontSize: size + 'px' }".
2 Styles Bindings in Template
Let's check dynamic style bindings in code:
HTML — Styles bindings
<!-- Dynamic Class Object Binding -->
<div class="card" :class="{ 'card--featured': isFeatured, 'card--disabled': isDisabled }">
<p>Flexible styles setup.</p>
</div>
<!-- Dynamic Inline Style Binding -->
<button :style="{ backgroundColor: buttonBgColor, border: borderThickness + 'px solid red' }">
Dynamic Looks
</button>
3 Code Challenge
Challenge: Write a component containing a warning box. Toggle the warning box background color between red and transparent using
isActive state flags bound via the :class directive.