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>v-else-if
Section titled “v-else-if”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.
Using <template> as a wrapper
Section titled “Using <template> as a wrapper”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
Section titled “v-show”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-if vs v-show
Section titled “v-if vs v-show”v-if | v-show | |
|---|---|---|
| When false | Removes element from DOM | Sets display: none |
| Initial render if false | No render cost | Renders but hides |
| Toggle cost | Higher (create/destroy DOM) | Lower (just CSS change) |
| Use when | Condition rarely changes | Condition 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.
In FamilyTree
Section titled “In FamilyTree”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>Exercise
Section titled “Exercise”- Create a component with a boolean
showDetailsref. - Show a “Details” panel with
v-ifwhenshowDetailsistrue. - Add a toggle button:
@click="showDetails = !showDetails". - Replace
v-ifwithv-showand compare: open DevTools → Elements and observe that the panel stays in the DOM.
v-ifremoves/inserts the element from the DOM; use for conditions that change infrequently.v-else-ifandv-elsechain conditions; they must immediately followv-if.<template v-if>groups multiple elements without a DOM wrapper.v-showtogglesdisplay: none; the element stays in the DOM — use for frequent toggles.