0
0
Vueframework~5 mins

v-else and v-else-if in Vue

Choose your learning style9 modes available
Introduction

v-else and v-else-if help you show or hide parts of your webpage based on conditions. They make your page change when things change.

Show a message only if a user is logged in or not.
Display different buttons depending on a setting.
Show a warning if a form is empty, else show a success message.
Switch between different views based on user choices.
Syntax
Vue
<template>
  <div v-if="condition1">Content 1</div>
  <div v-else-if="condition2">Content 2</div>
  <div v-else>Content 3</div>
</template>

v-else must come right after a v-if or v-else-if element without any space or other elements between.

v-else-if lets you check another condition if the first one is false.

Examples
This shows different messages based on the score value.
Vue
<template>
  <p v-if="score >= 90">You got an A!</p>
  <p v-else-if="score >= 80">You got a B!</p>
  <p v-else>You need to try harder.</p>
</template>
Shows a Logout button if logged in, otherwise shows Login.
Vue
<template>
  <button v-if="isLoggedIn">Logout</button>
  <button v-else>Login</button>
</template>
Sample Program

This component shows a message based on the weather variable. It first checks if the weather is sunny, then rainy, else shows unknown.

Vue
<template>
  <div>
    <p v-if="weather === 'sunny'">It's sunny outside!</p>
    <p v-else-if="weather === 'rainy'">Don't forget your umbrella.</p>
    <p v-else>Weather is unknown.</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const weather = ref('rainy')
</script>
OutputSuccess
Important Notes

Always place v-else or v-else-if immediately after v-if or v-else-if without any other elements in between.

Only one v-else block is allowed per v-if chain.

Use v-else-if to check multiple conditions in order.

Summary

v-else and v-else-if control what shows based on conditions.

v-else runs if all previous conditions are false.

v-else-if checks another condition after v-if.