Skip to the workspace
Pebellslearn by building
Templates  ›  Lesson

v-bind — Attributes, Classes and Styles

v-bind 14 minv-bind, written as a colon, turns an attribute's value into a JavaScript expression, with special object and array forms for class and style.

vue / v-bind — Attributes, Classes and Styles

Explore each scene at your own pace.

01 · The rule

The rule

v-bind — Attributes, Classes and Styles

Every BookCard needs a cover image, and each book's cover is different. You cannot write src="{{ book.cover }}", because braces do not work in attributes. Finished books should also look faded, which means a class that comes and goes. Both jobs belong to v-bind.

The rule

A colon turns the attribute's value into JavaScript.

v-bind:src="book.cover" is usually shortened to :src="book.cover". Without the colon, the value is a fixed string; with it, Vue evaluates the expression and keeps the attribute in sync.

<template>
  <article class="card" :class="{ finished: book.read }">
    <img :src="book.cover" :alt="book.title" />
    <button :disabled="book.read">Mark read</button>
    <div class="bar" :style="{ width: percent + '%' }"></div>
  </article>
</template>

The special cases worth knowing:

  • Boolean attributes. :disabled="book.read" adds disabled when the value is truthy and removes it when it is falsy. For ordinary attributes, a value of null or undefined removes the attribute.
  • Class objects. :class="{ finished: book.read }" adds the class finished only while book.read is truthy. An array works too: :class="[size, { finished: book.read }]".
  • Merging. A plain class="card" and a bound :class on the same element combine; you get card finished.
  • Style objects. :style="{ width: percent + '%' }" sets inline styles. Use camelCase (fontSize) or quoted kebab-case ('font-size') for property names.
  • Same-name shorthand. When the attribute and the variable share a name, :id="id" can be written :id (Vue 3.4 and later).
  • Many at once. v-bind="attrs" with no argument binds every key of an object as an attribute or prop.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.