iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

v-if / v-else

v-if conditionally renders an element. v-else-if and v-else chain. v-show is similar but toggles CSS display without unmounting — cheaper for high-frequency toggling.

if/else, show, template wrappers

EXAMPLE
<script setup>
import { ref } from 'vue';
const status = ref('loading');
const banner = ref(true);
</script>

<template>
    <!-- if / else if / else -->
    <div v-if="status === 'loading'">Loading…</div>
    <div v-else-if="status === 'error'">Something went wrong.</div>
    <div v-else>All good ✓</div>

    <!-- show — keeps node in DOM, toggles display -->
    <div v-show="banner" class="banner">Use v-show for things that toggle a LOT.</div>

    <!-- Group conditional siblings under <template> — no extra wrapper element -->
    <template v-if="user">
        <h2>Hi, {{ user.name }}</h2>
        <button @click="signOut">Sign out</button>
    </template>

    <!-- Combine with v-for (use a wrapper, not both on the same node) -->
    <template v-for="item in items" :key="item.id">
        <li v-if="item.active">{{ item.name }}</li>
    </template>
</template>

Why it matters

v-if mounts and unmounts; v-show just flips display. Pick v-if for rare toggles or expensive subtrees; v-show for tabs and modals that flip many times per second.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
<p v-if="count > 10">big</p>
<p v-else-if="count > 0">small</p>
<p v-else>none</p>
Try it Yourself »

Discussion

Loading…