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"addsdisabledwhen the value is truthy and removes it when it is falsy. For ordinary attributes, a value ofnullorundefinedremoves the attribute. - Class objects.
:class="{ finished: book.read }"adds the classfinishedonly whilebook.readis truthy. An array works too::class="[size, { finished: book.read }]". - Merging. A plain
class="card"and a bound:classon the same element combine; you getcard 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.
The shortcut
Read each attribute and ask: "Is this value fixed, or does it come from data?" Fixed → no colon. From data → colon, and write plain JavaScript between the quotes.
The wrapper
class="card"is fixed: no colon. "Faded when read" comes from data::class="{ finished: book.read }".
The classic slip is src="book.cover" without the colon. The browser then requests a file literally named book.cover, and the image is broken.
Drills
Answer fast — trust the rule.
What does <img src="book.cover"> (no colon) load?
Which binding adds the class finished only when book.read is true?
An element has class="card" and :class="{ finished: true }". What classes does it end up with?
busy is false. What does <button :disabled="busy"> render?
Remember
:attr="expression"binds an attribute to data;:classand:styleaccept objects and arrays.- Shortcut: fixed value, no colon; data-driven value, colon.
- Trap: forgetting the colon turns your expression into a literal string.
