← Back to all tutorials

Data Binding

Learn how to bind data to HTML attributes using v-bind — dynamically set src, href, class, style, and other attributes.

Data Binding

The {{ }} syntax works inside element content, but you cannot use it inside HTML attributes like src, href, or class. For that, you need the v-bind directive.

The v-bind Directive

<div id="app">
    <a v-bind:href="url">Visit Website</a>
    <img v-bind:src="imageUrl">
    <p v-bind:title="tooltip">Hover over me</p>
</div>

<script>
new Vue({
    el: '#app',
    data: {
        url: 'https://vuejs.org',
        imageUrl: 'https://vuejs.org/images/logo.png',
        tooltip: 'This is a tooltip from Vue data'
    }
});
</script>

v-bind:href="url" binds the href attribute to the url data property. When url changes, the attribute updates automatically.

Shorthand Syntax

<!-- Full syntax -->
<a v-bind:href="url">Link</a>

<!-- Shorthand (just a colon) -->
<a :href="url">Link</a>

<!-- Both are identical -->

The colon (:) shorthand is used almost universally in Vue projects. :href is the same as v-bind:href.

Binding to Different Attributes

BindingExample
Link<a :href="url">
Image<img :src="imageUrl">
Class<div :class="className">
Style<div :style="styleObject">
Disabled<button :disabled="isDisabled">
Value<input :value="inputValue">

Binding HTML Content

<p v-html="rawHtml"></p>

data: {
    rawHtml: '<strong>Bold text</strong> and <em>italic</em>'
}

The v-html directive outputs raw HTML. Use with caution — never use v-html with user-provided content as it can lead to XSS attacks.

Key Takeaways

  • v-bind:attr="data" binds a data property to an HTML attribute
  • The shorthand :attr is equivalent to v-bind:attr
  • Use {{ }} for element content, v-bind for attributes
  • v-html outputs raw HTML — use carefully to avoid XSS