0
0
Vueframework~5 mins

Attribute binding with v-bind in Vue

Choose your learning style9 modes available
Introduction

Attribute binding with v-bind lets you connect HTML attributes to Vue data. This means the attribute updates automatically when your data changes.

You want to change an image's source URL based on user input.
You need to update a link's destination dynamically.
You want to toggle a button's disabled state depending on a condition.
You want to set CSS classes or styles dynamically on an element.
You want to bind any HTML attribute to your Vue component's data.
Syntax
Vue
<element v-bind:attribute="dataProperty"></element>

You can shorten v-bind:attribute to just :attribute.

The value inside quotes is a JavaScript expression evaluated in Vue's data context.

Examples
Binds the src attribute of the image to the imageUrl data property.
Vue
<img v-bind:src="imageUrl" alt="A picture">
Shortened syntax for binding href attribute to linkUrl.
Vue
<a :href="linkUrl">Go to site</a>
Disables the button if isDisabled is true.
Vue
<button :disabled="isDisabled">Click me</button>
Sample Program

This Vue component lets you type an image URL in the input box. The img tag's src attribute updates automatically using v-bind (shortened as :). You see the image preview change as you type.

It uses ref to create reactive data and v-model to bind the input value.

Vue
<template>
  <div>
    <input v-model="imageUrl" placeholder="Enter image URL" aria-label="Image URL input" />
    <p>Image preview:</p>
    <img :src="imageUrl" alt="User provided image" style="max-width: 300px;" />
  </div>
</template>

<script setup>
import { ref } from 'vue'

const imageUrl = ref('https://vuejs.org/images/logo.png')
</script>
OutputSuccess
Important Notes

Always use quotes around the JavaScript expression in v-bind.

Use v-bind to bind any attribute, including src, href, alt, disabled, and more.

Remember to provide meaningful alt text for images for accessibility.

Summary

v-bind connects HTML attributes to Vue data so they update automatically.

You can shorten v-bind:attr to :attr for cleaner code.

Use attribute binding to make your UI dynamic and responsive to data changes.