Skip to the workspace
Pebellslearn by building
Directives  ›  Lesson

Conditional Rendering — v-if and v-show

Conditional Rendering 13 minv-if adds and removes elements based on a condition, while v-show keeps the element and only toggles its display.

vue / Conditional Rendering — v-if and v-show

Explore each scene at your own pace.

01 · The rule

The rule

Conditional Rendering — v-if and v-show

A new Shelf user has no books, so instead of an empty list they should see "Your shelf is empty — add your first book." Meanwhile the filter panel opens and closes every few seconds as people browse. Both are "show this sometimes", but they deserve different tools.

The rule

v-if builds or destroys; v-show only hides.

v-if renders an element only while its expression is truthy. When the expression turns falsy, the element, and any components inside it, are removed from the page entirely. Branches chain with v-else-if and v-else, which must sit on the element immediately after:

<p v-if="books.length === 0">Your shelf is empty — add your first book.</p>
<p v-else-if="books.length === 1">One book so far. Nice start.</p>
<BookList v-else :books="books" />

To switch a group of elements without adding a wrapper, put v-if on a <template> tag; the template itself is not rendered:

<template v-if="showStats">
  <h3>Stats</h3>
  <p>{{ finishedCount }} finished</p>
</template>

v-show always renders the element and toggles the CSS display property:

<aside v-show="filtersOpen" class="filters">...</aside>

Three limits of v-show: it cannot be used on <template>, it has no v-else partner, and the hidden element still exists in the page, so its components are created and keep running.

Cost trade-off. v-if is lazy: if the condition starts false, nothing is built. But every toggle tears down and rebuilds. v-show pays once, up front, then toggling is nearly free.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.