The v-if Directive
The v-if directive shows or hides an element by a condition. Vue shows the element when the condition is true and leaves it out when the condition is false.
Show when true
isOpen is true.
<p v-if="isOpen">Welcome</p>Hide when false
isOpen is false.
<p v-if="isOpen">Welcome</p>Either this or that
isOpen is false, so the else branch shows.
<p v-if="isOpen">Welcome</p>
<p v-else>Closed</p>A second condition
The count is 3, so the middle branch shows.
<p v-if="count > 10">Many</p>
<p v-else-if="count > 0">Some</p>
<p v-else>None</p>Example
<script setup>
import { ref } from 'vue'
const isOpen = ref(true)
const count = ref(3)
</script>
<template>
<div>
<p v-if="isOpen">The shop is open.</p>
<p v-else>The shop is closed.</p>
</div>
</template>
Key points
- Write v-if with a condition, like v-if="isOpen".
- The condition can be a ref, a comparison, or a short expression.
- Vue leaves the element out of the page when the condition is false.
- v-else shows a second element when the condition is false.
- v-else-if adds a second condition between v-if and v-else.
In this example, the script makes isOpen with a starting value of true. It also makes a count of 3. The template shows one paragraph when the shop is open and another when it is closed. The page first shows The shop is open. If isOpen becomes false, the page shows The shop is closed instead.
Note
A false condition leaves no trace in the page.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens when a v-if condition is false?