Skip to main content

What is v-bind used for?

v-bind is one of Vue's key directives, used to dynamically bind values to HTML attributes, component props, and even classes/styles.

In simple terms:

v-bind makes attributes "reactive", i.e. tied to data.


1. Dynamic binding of HTML attributes

javascript
<img v-bind:src="imageUrl">

Shorthand:

javascript
<img :src="imageUrl">

As soon as imageUrl changes, the DOM updates automatically.


2. Binding classes

Vue can accept strings, arrays, and objects.

Via an object:

javascript
<div :class="{ active: isActive, error: hasError }"></div>

Via an array:

javascript
<div :class="['btn', statusClass]"></div>

3. Binding styles

javascript
<div :style="{ color: textColor, fontSize: size + 'px' }"></div>

4. Binding props in components

javascript
<UserCard :user="currentUser" :is-admin="true" />

Without v-bind, all attributes are treated as strings.


5. Binding several attributes at once

You can pass an object:

javascript
<div v-bind="attrsObj"></div>
javascript
attrsObj = { id: 'user-block', class: 'profile', title: 'User info' }

6. The .prop modifier

Used to bind as a DOM property rather than an attribute:

javascript
<div :value.prop="someValue"></div>

7. Dynamic attribute name

javascript
<div v-bind:[attrName]="value"></div>
javascript
attrName = "data-id"; value = 42;

Result:

javascript
<div data-id="42"></div>

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.