Vue Conditional Statements
In Vue, we can use a series of directives to implement conditional rendering, which determines whether to render a block of DOM content based on the truth or falsity of specific conditions. The main directives include v-if, v-else-if, and v-else.
v-if
The v-if directive is used to conditionally render a block of content. This block is only rendered when the directive's expression returns a truthy value.
<script setup>
import { ref } from 'vue'
const awesome = ref(true)
</script>
<template>
<h1 v-if="awesome">Vue is awesome!</h1>
</template>If awesome's value is false, the <h1> element will not be created or inserted into the DOM at all.
v-else
You can use the v-else directive to indicate an "else block" for v-if.
<template>
<button @click="awesome = !awesome">Toggle</button>
<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else>Oh no 😢</h1>
</template>The v-else element must immediately follow an element with v-if or v-else-if, otherwise it will not be recognized.
v-else-if
v-else-if, as the name suggests, acts as an "else-if block" for v-if and can be used multiple times in a row.
<script setup>
import { ref } from 'vue'
const score = ref(85)
</script>
<template>
<div v-if="score >= 90">Excellent</div>
<div v-else-if="score >= 80">Good</div>
<div v-else-if="score >= 60">Pass</div>
<div v-else>Fail</div>
</template>Similar to v-else, v-else-if must also immediately follow a v-if or v-else-if element.
Using v-if on <template>
Because v-if is a directive, it must be added to an element. However, what if we want to toggle multiple elements? In this case, we can use a <template> element as an invisible wrapper element and use v-if on it. The final rendering result will not include the <template> element.
<template>
<template v-if="ok">
<h1>Title</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</template>
</template>v-show
Another option for conditionally displaying elements is the v-show directive. Usage is roughly the same:
<h1 v-show="ok">Hello!</h1>The difference is that elements with v-show will always be rendered and retained in the DOM. v-show simply toggles the element's CSS display property.
v-if vs v-show
v-ifis "true" conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and rebuilt during toggling.v-ifis also lazy: if the condition is false on initial render, nothing is done—until the condition becomes true for the first time, will the conditional block start rendering.v-showis much simpler—regardless of the initial condition, the element is always rendered, and only the CSSdisplayproperty is toggled.Choice: Overall,
v-ifhas higher switching overhead, whilev-showhas higher initial rendering overhead. Therefore, if you need to toggle very frequently,v-showis better; if the condition rarely changes at runtime,v-ifis better.