v-if and v-else
As you know from Template Syntax, an if can't go into {{ }}. To show an element only when a condition holds, give it the directive v-if:
<script setup>
import { ref } from "vue";
const open = ref(true);
</script>
<template>
<h1>Corner Café</h1>
<p v-if="open">Come in, we're open!</p>
<p v-else>Sorry, we're closed.</p>
<button @click="open = !open">Flip the sign</button>
</template>While open is true, the page has the first paragraph. Click the button, and Vue removes it and puts the second one in its place: v-else shows its element when the v-if before it doesn't. Between them can come any number of v-else-ifs, each with a condition of its own:
<p v-if="hour < 7">We open at 7 am.</p>
<p v-else-if="hour < 19">We're open until 7 pm.</p>
<p v-else>We're closed. See you tomorrow!</p>Vue checks the conditions from the top and shows only the first element whose condition is true, just as if, else if and else work in JavaScript. At 9 o'clock, that's the second one. When no condition is true and there's no v-else, it shows none of them.
An element whose v-if is false isn't hidden: it isn't on the page at all. Vue makes the element when the condition becomes true, and removes it when it becomes false.
Typical mistake: an element in between. v-else-if and v-else have to be on the element right after a v-if or v-else-if. With another element between them, the page doesn't run, and the red bar under the preview names the line of the v-else and says v-else/v-else-if has no adjacent v-if or v-else-if.
Instructions
- 1
Under the buttons, show
We're open until 7 pm.while it's earlier than 19:00, andWe're closed.otherwise. Usev-ifandv-else, and try the buttons. - 2
Before 7:00, the page should say
We open at 7 am.instead of the other two messages. Put that paragraph first, withv-if, and turn thev-ifof the open paragraph into av-else-if.