TExcelTAD
Home › Vue › Vue v-bind

Vue v-bind

Text interpolation with {{ }} only works between tags. To put data into an attribute — an image's src, a link's href, an input's disabled — you use the v-bind directive, or its shorthand :.

html
<img v-bind:src="photoUrl">   <!-- long form -->
<img :src="photoUrl">         <!-- shorthand, used almost everywhere -->

Without v-bind, src="photoUrl" would be the literal text photoUrl. With it, the value is a JavaScript expression evaluated against your data.

Binding attributes

html · try it yourself
<style>
  img { border-radius: 8px; display: block; margin: 8px 0; }
</style>

<div id="app">
  <img :src="images[index].src" :alt="images[index].alt" :width="size">
  <p>{{ images[index].alt }} — {{ size }}px</p>
  <button @click="index = (index + 1) % images.length">Next picture</button>
  <input type="range" min="60" max="200" v-model.number="size">
</div>

<script type="module">
  import { createApp } from 'vue';

  const svg = (color) =>
    `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ccircle cx='50' cy='50' r='40' fill='${color}'/%3E%3C/svg%3E`;

  createApp({
    data() {
      return {
        index: 0,
        size: 120,
        images: [
          { src: svg('%2342b883'), alt: 'A green circle' },
          { src: svg('orange'), alt: 'An orange circle' },
          { src: svg('steelblue'), alt: 'A blue circle' }
        ]
      };
    }
  }).mount('#app');
</script>

Every time index or size changes, Vue updates the src, alt and width attributes for you.

Boolean attributes

Attributes such as disabled, checked or hidden are either present or absent. Vue includes the attribute when the bound value is truthy and removes it when the value is false, null or undefined.

html · try it yourself
<div id="app">
  <label><input type="checkbox" v-model="agreed"> I accept the terms</label>
  <br><br>
  <button :disabled="!agreed" @click="console.log('Signed up!')">Sign up</button>
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data: () => ({ agreed: false })
  }).mount('#app');
</script>

Templates normally only see your component's data, but Vue allows a short list of common globals such as Math, Date, JSON, parseInt and console, so console.log inside a template handler works. In real apps you usually call a method instead.

Null and undefined remove the attribute

Bound value Result in the DOM
'hello' title="hello"
'' (empty string) title=""
null or undefined attribute removed
true on disabled disabled=""
false on disabled attribute removed

Binding many attributes at once

v-bind without an argument takes an object and spreads every key as an attribute. This is handy when a set of attributes travels together.

html · try it yourself
<div id="app">
  <input v-bind="fieldAttrs">
  <p>Attributes: <code>{{ JSON.stringify(fieldAttrs) }}</code></p>
  <button @click="fieldAttrs.placeholder = 'Changed!'">Change placeholder</button>
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data() {
      return {
        fieldAttrs: {
          type: 'email',
          placeholder: 'you@example.com',
          maxlength: 40,
          required: true
        }
      };
    }
  }).mount('#app');
</script>

Same-name shorthand (Vue 3.4+)

When the attribute and the data property have the same name, you can leave out the value:

html
<img :src :alt>          <!-- same as :src="src" :alt="alt" -->

Tip: v-bind also has special powers for class and style: it accepts objects and arrays there. You will learn those in the CSS Binding lesson.

Expressions in bindings

Any single expression works — string concatenation, template literals, ternaries, function calls:

html
<a :href="'/products/' + product.id">Details</a>
<div :id="`row-${index}`"></div>
<button :title="saved ? 'Saved' : 'Not saved yet'">💾</button>

Note: Writing :href="url" is safe from injection: Vue sets the attribute value as text. It does not sanitise URLs, though, so never bind user-supplied links like javascript:… without checking them.

Test yourself

What is the shorthand for v-bind:href="link"?

  1. @href="link"
  2. #href="link"
  3. :href="link"
  4. href="{{ link }}"

What happens to :disabled="isBusy" when isBusy is false?

  1. The attribute becomes disabled="false"
  2. The attribute is removed
  3. Vue throws an error
  4. The button is hidden

What does <input v-bind="attrs"> do when attrs is an object?

  1. Binds the object as one attribute called attrs
  2. Nothing, an argument is required
  3. Spreads each key of the object as a separate attribute
  4. Copies the object into the input's value