How to Use v-else-if in Vue: Syntax and Examples
In Vue,
v-else-if is used to add multiple conditional branches after a v-if block, allowing you to render different elements based on different conditions. It must come immediately after a v-if or another v-else-if and before a v-else if present.Syntax
The v-else-if directive is placed on an element to specify an additional condition to check if the previous v-if or v-else-if was false. It must be directly after the previous conditional element without any other elements in between.
Parts explained:
v-if="condition1": The first condition to check.v-else-if="condition2": Checked if the first condition is false.v-else: Runs if all previous conditions are false.
vue
<template> <div v-if="condition1">Content for condition 1</div> <div v-else-if="condition2">Content for condition 2</div> <div v-else>Content if none of the above</div> </template>
Example
This example shows how to use v-if, v-else-if, and v-else to display different messages based on a numeric value.
vue
<template>
<div>
<p v-if="score >= 90">Excellent</p>
<p v-else-if="score >= 70">Good</p>
<p v-else-if="score >= 50">Pass</p>
<p v-else>Fail</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const score = ref(75)
</script>Output
Good
Common Pitfalls
Common mistakes when using v-else-if include:
- Placing any other element or text between
v-ifandv-else-if, which breaks the chain. - Using
v-else-ifwithout a precedingv-iforv-else-if. - Not covering all cases, leading to unexpected empty renders if no condition matches.
vue
<template> <!-- Wrong: element between v-if and v-else-if --> <div v-if="a">A</div> <span>Some text</span> <div v-else-if="b">B</div> <!-- Correct: no element between --> <div v-if="a">A</div> <div v-else-if="b">B</div> </template>
Quick Reference
Tips for using v-else-if effectively:
- Always place
v-else-ifimmediately afterv-ifor anotherv-else-if. - Use
v-else-ifto check multiple exclusive conditions cleanly. - End with
v-elseto handle all other cases. - Keep conditions simple and readable.
Key Takeaways
Use
v-else-if to add multiple conditional branches after v-if in Vue templates.v-else-if must come immediately after v-if or another v-else-if without any elements in between.Combine
v-if, v-else-if, and v-else to cover all possible conditions clearly.Avoid placing unrelated elements between conditional directives to prevent rendering errors.
Keep your conditions simple and test all branches to ensure expected output.