i-bind
i-bind Directive
The i-bind
directive (also available as a shorthand :
) allows you to dynamically bind an attribute or property to an expression. This enables reactive updates of element attributes based on your application's state.
Usage
Add the i-bind:
prefix (or :
shorthand) to any attribute you want to bind dynamically:
<img i-bind:src="imageSrc" i-bind:alt="imageAlt" />
<!-- Shorthand syntax -->
<img :src="imageSrc" :alt="imageAlt" />
Syntax
The i-bind
directive uses the following syntax:
<element i-bind:attribute="expression"></element>
or using the shorthand:
<element :attribute="expression"></element>
Where:
attribute
is the name of the attribute you want to bindexpression
is a valid JavaScript expression that will be evaluated against the component's state
Examples
Binding a simple property:
html<input :value="message" />
Binding a computed property:
html<p :class="isActive ? 'active' : 'inactive'">Status</p>
Binding multiple classes:
html<div :class="{ active: isActive, 'text-danger': hasError }"> <!-- content --> </div>
Binding inline styles:
html<div :style="{ color: textColor, fontSize: fontSize + 'px' }"> <!-- content --> </div>
Special Bindings
Class Bindings
When binding to the class
attribute, you can pass either a string, an object, or an array:
<!-- String -->
<div :class="activeClass"></div>
<!-- Object -->
<div :class="{ active: isActive, 'text-danger': hasError }"></div>
<!-- Array -->
<div :class="[activeClass, errorClass]"></div>
Style Bindings
When binding to the style
attribute, you can pass an object with CSS properties:
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
Boolean Attributes
For boolean attributes (like disabled
, readonly
, etc.), the attribute will be added if the bound value is truthy, and removed if it's falsy:
<button :disabled="isLoading">Submit</button>
Performance Considerations
The i-bind
directive sets up reactive bindings, which means changes to the bound expressions will automatically update the DOM. However, be mindful of binding complex expressions or frequently changing values to attributes of elements in large lists, as it may impact performance.