Skip to content

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:

html
<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:

html
<element i-bind:attribute="expression"></element>

or using the shorthand:

html
<element :attribute="expression"></element>

Where:

  • attribute is the name of the attribute you want to bind
  • expression is a valid JavaScript expression that will be evaluated against the component's state

Examples

  1. Binding a simple property:

    html
    <input :value="message" />
  2. Binding a computed property:

    html
    <p :class="isActive ? 'active' : 'inactive'">Status</p>
  3. Binding multiple classes:

    html
    <div :class="{ active: isActive, 'text-danger': hasError }">
      <!-- content -->
    </div>
  4. 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:

html
<!-- 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:

html
<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:

html
<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.