Text interpolation and attribute binding

Beginner · 12 min

How a Vue template puts data into text with double curly braces and into attributes with v-bind, which expressions are allowed, and how values apply.

Before thisSingle-file components

Atom Jar | AI for Everyone · 57 min · from 1:33

Text interpolation and attribute binding

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Atom Jar | AI for EveryoneReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Double curly braces put the result of a JavaScript expression into an element's text, HTML-escaped, and update it whenever the data it reads changes.
  • Curly braces never work inside an attribute. To bind an attribute to data you use `v-bind:name="expr"`, almost always written with the `:name` shorthand, and the quoted value is a JavaScript expression rather than a string.
  • Template expressions must be a single expression that produces a value. Statements like `if` or `const` are not allowed, and only a short allow-list of globals such as `Math` and `Date` is reachable.
  • A bound value of `null` or `undefined` removes the attribute. Boolean attributes like `disabled` are also removed for any other falsy value except the empty string, while non-boolean attributes render `false` as the literal text "false".
  • `v-bind="obj"` spreads every key of an object as an attribute, `:[name]="value"` binds an attribute whose name is itself computed, and since Vue 3.4 `:id` alone is shorthand for `:id="id"`.
  • `v-html` inserts raw HTML instead of escaped text, which makes it an XSS hole for any content a user can influence.

Two places data has to go

A component’s state lives in JavaScript. The page the user sees is DOM. A template’s whole job is to describe how one maps onto the other, and in practice data needs to land in exactly two kinds of place: the text between tags, and the attributes on tags.

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

const product = ref('Wool socks')
const image = ref('/img/socks-green.jpg')
</script>

<template>
  <h1>{{ product }}</h1>
  <img :src="image" :alt="product" />
</template>

Vue gives each of those places its own syntax. Text uses double curly braces, often called “mustaches”. Attributes use the v-bind directive. The split is deliberate. Vue templates are valid HTML that Vue’s compiler parses before turning them into render functions, and HTML has no idea what {{ }} means inside an attribute value. Keeping attribute bindings in a directive means the template stays parseable HTML.

ref() makes product a reactive value, and the template reads it without .value because refs declared at the top level of <script setup> are unwrapped in templates automatically. How that works is the subject of ref and reactive. For now, treat ref as “a value the template watches”.

Interpolation: expressions, not statements

Whatever sits between the braces is a JavaScript expression. Vue evaluates it in the component’s scope, converts the result to a string, and sets it as escaped text. When any reactive value the expression read changes, the text re-renders.

<template>
  <p>{{ count + 1 }} items</p>
  <p>{{ ok ? 'In stock' : 'Sold out' }}</p>
  <p>{{ message.split('').reverse().join('') }}</p>
  <p>{{ formatPrice(price) }}</p>
</template>

Each binding must be one expression, something that could sit on the right side of return. Statements do not compile:

<!-- Not valid: these are statements, not expressions -->
{{ const a = 1 }}
{{ if (ok) { return message } }}

Two more limits are worth knowing. Expressions are sandboxed: beyond the component’s own state they can reach only a short allow-list of globals such as Math, Date and JSON, not arbitrary things you hung on window. And a function called in a binding runs on every re-render of the component, so it should compute a value and nothing else. A function that mutates state or fires a request from inside a template is a bug waiting to happen. Once expressions grow past a line, move them into a computed property.

Interpolation always escapes. A string containing <b> shows up as the characters <b>, not bold text. When you really do need markup, v-html sets innerHTML directly:

<div v-html="trustedHtml"></div>

Only use it with content you control. Feeding user input to v-html is a textbook cross-site scripting hole; web security fundamentals covers why.

v-bind: attributes from data

For attributes, v-bind:name="expression" binds the attribute to the expression’s value. The colon shorthand is what nearly all Vue code uses:

<template>
  <a v-bind:href="url">Full form</a>
  <a :href="url">Shorthand, identical</a>
  <img :src="`/img/${slug}.jpg`" :alt="'Photo of ' + name" />
</template>

The thing people trip over is that the quoted value is code, not text. href="url" sets the attribute to the three letters u, r, l. :href="url" sets it to whatever the variable url holds. String literals inside a binding need their own inner quotes, as in the alt example above.

Since Vue 3.4 there is a same-name shorthand. If the attribute and the variable share a name, you can drop the value:

<!-- Both mean :id="id" :src="src" -->
<img :id :src />

How a bound value becomes an attribute

Vue applies a few rules when it turns a JavaScript value into an attribute:

  • null or undefined removes the attribute entirely. This is the standard way to say “no attribute here”.
  • Boolean attributes like disabled, checked or readonly are present when the value is truthy or an empty string, and removed for any other falsy value.
  • Every other attribute renders the value as a string. That includes false: :aria-hidden="false" produces aria-hidden="false", which is what ARIA expects. Vue 2 used to remove attributes bound to false; Vue 3 does not.
<button :disabled="isSaving">Save</button>
<input :placeholder="hint ?? null" />

Under the hood, Vue sets a DOM property rather than an HTML attribute when the element has a property of that name, which is why :value on an input and :disabled on a button behave the way you would expect. The .prop and .attr modifiers force one or the other for the rare case where the default guess is wrong.

Binding many attributes, or a computed name

Two less common forms round out v-bind. Without an argument, it spreads an object, one attribute per key:

<script setup>
const linkAttrs = {
  href: 'https://vuejs.org',
  target: '_blank',
  rel: 'noopener',
}
</script>

<template>
  <a v-bind="linkAttrs">Vue docs</a>
</template>

With square brackets, the attribute name is an expression too:

<!-- Binds either aria-label or title, depending on attrName -->
<span :[attrName]="labelText">?</span>

A dynamic argument must evaluate to a string, or null to remove the binding. It cannot contain spaces or quotes, so anything complicated belongs in a computed value.

Compared with JSX

React’s JSX uses one syntax, {expr}, for both text and attributes, because JSX is JavaScript that only looks like HTML. Vue’s template is HTML that the compiler enhances, so the two positions get different syntax. In exchange, the compiler can see which parts of a template are static and which are bound, and it uses that to skip work when re-rendering. JSX syntax and compilation is the React side of this comparison.

What the video covers

The embed is cut to two chapters of Adam Jahr’s Composition API version of Vue Mastery’s Intro to Vue 3 course, published on the channel that originally hosted Vue Mastery (since renamed). Lesson 2 creates a project with create-vue and renders a product name with {{ product }} from a ref in <script setup>. Lesson 3 binds an image’s src with v-bind and introduces the colon shorthand. The first several minutes are project scaffolding, which setting up a Vue project already covers. The video does not cover v-html, the attribute value rules, object spreading, dynamic arguments or the 3.4 same-name shorthand. Those are all carried by this lesson.

Where this fits

Every other directive in this group builds on the same idea: a quoted JavaScript expression attached to an element. Next comes conditional rendering with v-if and v-show, and v-bind’s special handling of class and style gets its own lesson in class and style bindings.

Check yourself

  1. 01Why does `<a href="{{ url }}">` not work in a Vue template, and what is the fix?

    Interpolation only applies to text content. Inside an attribute value, Vue treats `{{ url }}` as a plain string, so the link would point at the literal text. The fix is to bind the attribute with `v-bind`: `<a :href="url">`, where the quoted value is evaluated as a JavaScript expression.

  2. 02What renders for `<button :disabled="flag">` when `flag` is `0`, when it is `''`, and when it is `null`?

    `disabled` is a boolean attribute. With `0` (falsy and not an empty string) the attribute is omitted, so the button is enabled. With `''` the attribute is included as `disabled=""`, so the button is disabled. With `null` the attribute is removed, so the button is enabled.

  3. 03Is `{{ if (ok) { 'yes' } }}` valid inside a template? How would you write it?

    No. A template binding must be a single expression that evaluates to a value, and `if` is a statement. Use a ternary instead: `{{ ok ? 'yes' : 'no' }}`, or move the logic into a computed value in `<script setup>`.

  4. 04Why is `<div v-html="comment.body">` dangerous when `comment.body` comes from users?

    `v-html` sets the element's `innerHTML` without escaping, so any markup in the string becomes real DOM. A user who submits a comment containing an image tag with an `onerror` handler, for example, gets their script run in every visitor's browser. Interpolation with curly braces escapes the text and has no such risk.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark