Skip to content

v-if, v-else, and v-show

Conditional rendering — showing or hiding parts of the UI based on state — is one of the most common template operations. Vue provides two directives: v-if and v-show.

v-if conditionally renders an element. When the condition is false, the element is removed from the DOM entirely:

<script setup lang="ts">
import { ref } from 'vue'
const isLoggedIn = ref(false)
</script>
<template>
<p v-if="isLoggedIn">Welcome back!</p>
<p v-else>Please log in.</p>
</template>

Chain conditions with v-else-if:

<template>
<span v-if="role === 'focus'">You</span>
<span v-else-if="role === 'parent'">Parent</span>
<span v-else-if="role === 'child'">Child</span>
<span v-else>Relative</span>
</template>

v-else and v-else-if must immediately follow a v-if element — no other elements between them.

When you need to conditionally show multiple elements without a wrapper <div>:

<template v-if="person">
<h2>{{ person.name }}</h2>
<p>{{ person.bio }}</p>
</template>

The <template> element is not rendered to the DOM — it’s purely a grouping mechanism.

v-show toggles an element’s CSS display property. The element stays in the DOM:

<div v-show="isExpanded" class="details-panel">
<!-- always in DOM; hidden with display: none when isExpanded is false -->
</div>
v-ifv-show
When falseRemoves element from DOMSets display: none
Initial render if falseNo render costRenders but hides
Toggle costHigher (create/destroy DOM)Lower (just CSS change)
Use whenCondition rarely changesCondition changes frequently

Rule of thumb: use v-if for things that are conditionally meaningful (e.g., only show a section if there is data). Use v-show for elements that are toggled frequently, like a dropdown or accordion.

PersonDetailView.vue uses v-if extensively to show relationship sections only when there’s data, and to toggle edit/view modes:

<div v-if="currentSpouse" class="spouse-entry">
<!-- spouse details -->
</div>
<span v-else class="text-muted">No current spouse.</span>
<template v-if="editingRel === currentSpouse.id">
<!-- edit form -->
</template>
<template v-else>
<!-- display mode -->
</template>
  1. Create a component with a boolean showDetails ref.
  2. Show a “Details” panel with v-if when showDetails is true.
  3. Add a toggle button: @click="showDetails = !showDetails".
  4. Replace v-if with v-show and compare: open DevTools → Elements and observe that the panel stays in the DOM.
  • v-if removes/inserts the element from the DOM; use for conditions that change infrequently.
  • v-else-if and v-else chain conditions; they must immediately follow v-if.
  • <template v-if> groups multiple elements without a DOM wrapper.
  • v-show toggles display: none; the element stays in the DOM — use for frequent toggles.