0
0
VueHow-ToBeginner · 3 min read

How to Use v-bind in Vue: Syntax, Examples, and Tips

In Vue, use v-bind to dynamically bind HTML attributes to JavaScript data properties. The shorthand for v-bind is :, which makes your templates cleaner and reactive.
📐

Syntax

The v-bind directive binds an HTML attribute to a Vue data property or expression. You write it as v-bind:attribute="expression". The shorthand is :attribute="expression".

Here, attribute is the HTML attribute you want to bind (like href, class, or src), and expression is a Vue data property or JavaScript expression that provides the value.

vue
<a v-bind:href="url">Link</a>
<!-- shorthand -->
<a :href="url">Link</a>
Output
<a href="https://example.com">Link</a>
💻

Example

This example shows how to use v-bind to set the href attribute of a link dynamically from Vue data. When the data changes, the link updates automatically.

vue
<template>
  <div>
    <a :href="url">Visit Site</a>
    <button @click="changeUrl">Change URL</button>
  </div>
</template>

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

const url = ref('https://example.com')

function changeUrl() {
  url.value = 'https://vuejs.org'
}
</script>
Output
A clickable link labeled 'Visit Site' that initially points to https://example.com. Clicking the button changes the link to point to https://vuejs.org.
⚠️

Common Pitfalls

  • Forgetting to use quotes around the expression in v-bind can cause errors.
  • Using v-bind without a valid Vue data property or expression results in empty or broken attributes.
  • Trying to bind non-string attributes without proper formatting can cause unexpected behavior.

Always ensure the bound expression exists in your Vue component's data or setup.

vue
<!-- Wrong: missing quotes -->
<a :href=https://example.com>Link</a>

<!-- Right: quotes around expression -->
<a :href="url">Link</a>
📊

Quick Reference

Use v-bind or its shorthand : to bind attributes dynamically. It works with any valid HTML attribute and updates reactively when data changes.

  • v-bind:src="imageUrl" binds the src attribute.
  • v-bind:class="className" binds CSS classes.
  • v-bind:disabled="isDisabled" binds boolean attributes.

Key Takeaways

Use v-bind or : to bind HTML attributes to Vue data reactively.
Always wrap the binding expression in quotes to avoid syntax errors.
You can bind any valid HTML attribute, including href, src, class, and disabled.
Bindings update automatically when the underlying data changes.
Avoid binding undefined or incorrect data properties to prevent broken attributes.