Vue v-bind Directive

Vue Tutorial

Vue v-bind Directive

In Vue.js, the Vue v-bind Directive is used to dynamically bind HTML attributes with Vue data.

It allows attribute values to change automatically when data changes.


 What is Vue v-bind Directive?

v-bind connects an HTML attribute with a Vue data property.

 Without v-bind, attributes are static
 With v-bind, attributes become dynamic


 Basic Syntax

<tag v-bind:attribute="dataProperty"></tag>

Shorthand (Most Common)

<tag :attribute="dataProperty"></tag>

 Example 1: Binding an Image Source


 

 When imageUrl changes, the image updates automatically.


 Example 2: Binding a Link (href)

<a :href="website">Visit Website</a>
data() {
return {
website: "https://vuejs.org"
}
}

 Example 3: Binding class

You can dynamically apply CSS classes.

 Using Object Syntax

<p :class="{ active: isActive, error: hasError }">
Vue v-bind Class
</p>
data() {
return {
isActive: true,
hasError: false
}
}

Using Array Syntax

<p :class="[activeClass, errorClass]">Hello Vue</p>
data() {
return {
activeClass: "active",
errorClass: "error"
}
}

 Example 4: Binding style

Inline styles can also be dynamic.

<p :style="{ color: textColor, fontSize: fontSize + 'px' }">
Styled Text
</p>
data() {
return {
textColor: "blue",
fontSize: 20
}
}

 Example 5: Binding Boolean Attributes

<button :disabled="isDisabled">Submit</button>
data() {
return {
isDisabled: true
}
}

 Button becomes disabled when isDisabled is true.


v-bind with Components

<user-card :name="username" :age="userAge"></user-card>

This passes dynamic props to components.


 Key Points to Remember

  • v-bind makes attributes reactive

  • Use shorthand : for cleaner code

  • Works with:

    • src

    • href

    • class

    • style

    • disabled, checked, etc.

  • Essential for dynamic UI


 Summary Table

UsageExample
Bind attribute:src="imageUrl"
Bind class:class="{ active: isActive }"
Bind style:style="{ color: 'red' }"
Boolean attribute:disabled="true"
Component props:title="pageTitle"

 Conclusion

The v-bind directive is a core concept in Vue.
Without it, Vue apps cannot be truly dynamic.

You may also like...