v-if
The v-if directive is used to conditionally render a block. It can toggle elements on the page, similarly to v-show, however it completely mounts and unmounts the element it's applied to rather than just changing its CSS display property to none.
Here is the updated example from v-show, but using v-if:
<script setup>
import { ref } from 'vue'
// reactive data
const open = ref(false)
</script>
<template>
<button v-on:click="open = !open">Toggle Dropdown</button>
<div v-if="open">
Dropdown Contents...
</div>
</template>v-else
You can use the v-else directive to indicate an "else block" for v-if:
<script setup>
import { ref } from 'vue'
// reactive data
const open = ref(false)
</script>
<template>
<button v-on:click="open = !open">Toggle</button>
<h1 v-if="open">Vue is awesome!</h1>
<h1 v-else>Oh no 😢</h1>
</template>NOTE
A v-else element must immediately follow a v-if or a v-else-if element - otherwise it will not be recognized.
v-else-if
The v-else-if, as the name suggests, serves as an "else if block" for v-if. It can also be chained multiple times:
<div v-if="type === 'A'">
A
</div>
<div v-else-if="type === 'B'">
B
</div>
<div v-else-if="type === 'C'">
C
</div>
<div v-else>
Not A/B/C
</div>NOTE
Similar to v-else, a v-else-if element must immediately follow a v-if or a v-else-if element.
<template> tag
Because v-if is a directive, it has to be attached to a single element. But what if we want to toggle more than one element? In this case we can use v-if on a <template> element, which serves as an invisible wrapper. The final rendered result will not include the <template> element.
<template v-if="ok">
<h1>Title</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</template>NOTE
v-else and v-else-if can also be used on <template>.
