TExcelTAD
Home › Vue › Vue Templates

Vue Templates

A template is the HTML-like markup that describes what a component renders. You have been writing templates since the first lesson; this lesson collects the template rules in one place: where templates can live, what you may write in {{ }}, how to output raw HTML, and the special directives v-once, v-pre and v-cloak.

Three places a template can live

Where Example Compiled
In-DOM — inside the mount element <div id="app">{{ msg }}</div> In the browser, at runtime
template option — a string template: '<p>{{ msg }}</p>' In the browser, at runtime
Single-File Component — a <template> block in a .vue file <template><p>{{ msg }}</p></template> Ahead of time by Vite

The playground uses the first two at once. If a component has a template option, it replaces the content of the mount element.

html · try it yourself
<div id="app">
  <p>This in-DOM content is replaced, because the app has a template option.</p>
</div>

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

  createApp({
    data: () => ({ city: 'Da Nang', temp: 31 }),
    template: `
      <h3>Weather in {{ city }}</h3>
      <p>{{ temp }} °C — {{ temp > 28 ? 'hot ☀️' : 'mild 🌤️' }}</p>
      <button @click="temp--">Cool down</button>
    `
  }).mount('#app');
</script>

Tip: Templates in a JavaScript string are easier to read with backticks (template literals), because they can span several lines and contain both kinds of quotes.

Text interpolation and expressions

{{ }} accepts any single JavaScript expression: arithmetic, ternaries, method calls, template literals, array methods. Only a limited set of globals is available (Math, Date, JSON, Number, parseInt, console and similar) — not your own global variables.

html · try it yourself
<div id="app">
  <p>{{ price * qty }} €</p>
  <p>{{ items.length ? items.join(', ') : 'Empty list' }}</p>
  <p>{{ title.toUpperCase().split('').reverse().join('') }}</p>
  <p>{{ Math.round(ratio * 100) }}%</p>
  <p>{{ `Hello ${name}!` }}</p>
  <p>{{ JSON.stringify({ name, qty }) }}</p>
</div>

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

  createApp({
    data: () => ({ price: 4.5, qty: 3, items: ['tea', 'cake'], title: 'vue', ratio: 0.736, name: 'Bao' })
  }).mount('#app');
</script>

Not allowed: statements (if, for, let x = 1), and anything longer than one expression. Interpolations also always output text: HTML tags inside the value are escaped and shown literally.

Raw HTML with v-html

To render a string as real HTML, use v-html. It replaces the element's content.

html · try it yourself
<div id="app">
  <p>Interpolation: {{ snippet }}</p>
  <p>v-html: <span v-html="snippet"></span></p>
</div>

<script type="module">
  import { createApp } from 'vue';
  createApp({ data: () => ({ snippet: '<em style="color:#42b883">green italic text</em>' }) }).mount('#app');
</script>

Note: Never use v-html on content written by users. If someone submits <img src=x onerror="stealCookies()">, v-html would run their script — a cross-site scripting (XSS) attack. Only use it on HTML you trust, or sanitise it first.

v-once, v-pre and v-cloak

Directive What it does
v-once Render the element once; later data changes do not update it
v-pre Skip compilation — {{ }} and directives are shown as written
v-cloak Stays on the element until Vue has mounted; pair with [v-cloak] { display: none } to hide raw {{ }} during loading
html · try it yourself
<style> [v-cloak] { display: none; } </style>

<div id="app" v-cloak>
  <p>Live: {{ count }}</p>
  <p v-once>Initial value (v-once): {{ count }}</p>
  <p v-pre>Shown literally (v-pre): {{ count }}</p>
  <button @click="count++">Increment</button>
</div>

<script type="module">
  import { createApp } from 'vue';
  createApp({ data: () => ({ count: 1 }) }).mount('#app');
</script>

Caveats of in-DOM templates

When the template lives directly in the page's HTML, the browser parses it first, and only then does Vue read it. The HTML parser has rules that can bite you:

  1. Case-insensitivity. Attribute and tag names are lower-cased. Use kebab-case for component names, props and events: <user-card :avatar-url="u.pic" @item-removed="...">, not <UserCard :avatarUrl ...>.
  2. No self-closing components. <my-comp /> is read as an opening tag. Always write <my-comp></my-comp>.
  3. Element placement restrictions. Inside <ul>, <ol>, <table> and <select> only certain children are allowed. Use <tr is="vue:my-row"></tr> to place a component there.
  4. Raw {{ }} flicker until Vue mounts — hide it with v-cloak.

String templates and Single-File Components don't have these restrictions, because Vue's own compiler parses them. This is one reason why real projects use .vue files.

Templates compile to render functions

Behind the scenes, Vue turns every template into a JavaScript render function that returns virtual DOM nodes. You can write one yourself with h() — rarely needed, but useful to know:

js
import { h } from 'vue';

export default {
  data: () => ({ n: 0 }),
  render() {
    return h('button', { onClick: () => this.n++ }, `Clicked ${this.n} times`);
  }
};

Test yourself

Which is valid inside {{ }}?

  1. if (ok) { 'yes' }
  2. let total = 5
  3. ok ? 'yes' : 'no'
  4. for (x of xs) x

Why is v-html dangerous with user-provided content?

  1. It is slow
  2. It can execute injected scripts (XSS)
  3. It removes all CSS
  4. It only works once

Inside an in-DOM template, how should you write a component called TodoItem?

  1. <TodoItem />
  2. <todo-item />
  3. <todo-item></todo-item>
  4. <todoItem></todoItem>