0
0
VueHow-ToBeginner · 3 min read

How to Use v-else in Vue: Simple Conditional Rendering

In Vue, v-else is used to show an element only when the preceding v-if condition is false. It must immediately follow a v-if or v-else-if element without any space or other elements between them.
📐

Syntax

The v-else directive is placed on an element that should render only when the previous v-if or v-else-if condition is false. It cannot have its own condition and must come directly after the related v-if or v-else-if element.

  • v-if: Checks a condition to render an element.
  • v-else-if: Checks another condition if the previous v-if was false.
  • v-else: Renders if all previous conditions are false.
vue
<template>
  <div v-if="conditionA">Show if conditionA is true</div>
  <div v-else-if="conditionB">Show if conditionA is false and conditionB is true</div>
  <div v-else>Show if both conditionA and conditionB are false</div>
</template>
💻

Example

This example shows how v-else works with v-if to display different messages based on a boolean value.

vue
<template>
  <div>
    <p v-if="isLoggedIn">Welcome back, user!</p>
    <p v-else>Please log in to continue.</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
const isLoggedIn = ref(false)
</script>
Output
Please log in to continue.
⚠️

Common Pitfalls

Common mistakes when using v-else include:

  • Not placing v-else immediately after a v-if or v-else-if element. Any other element or whitespace breaks the connection.
  • Trying to use v-else without a preceding v-if or v-else-if.
  • Adding a condition to v-else, which is invalid since it has no expression.
vue
<template>
  <!-- Wrong: v-else not immediately after v-if -->
  <div v-if="show">Show this</div>
  <div>Some other element</div>
  <div v-else>Won't work</div>

  <!-- Correct: v-else immediately after v-if -->
  <div v-if="show">Show this</div>
  <div v-else>Show if not</div>
</template>
📊

Quick Reference

Remember these tips when using v-else:

  • Placement: Must be right after v-if or v-else-if.
  • No condition: v-else never has an expression.
  • Use with v-if: Always paired with v-if or v-else-if.

Key Takeaways

Use v-else immediately after v-if or v-else-if without any elements in between.
v-else does not take a condition; it runs only if previous conditions are false.
Avoid placing other elements or whitespace between v-if and v-else to keep them connected.
Use v-else to provide a fallback UI when all prior conditions fail.