How to use v-else and v-else-if in Vue
Using v-else and v-else-if directives enables complex conditional rendering logic with multiple conditions and fallback content for comprehensive template control. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented conditional rendering in thousands of Vue components for dynamic user interfaces and state-based content. From my expertise, the most effective approach is chaining v-if, v-else-if, and v-else directives for clear conditional logic flow. This method provides readable template code with proper condition handling and fallback scenarios for robust user interfaces.
Chain v-if
, v-else-if
, and v-else
directives for multi-condition rendering logic.
<template>
<div>
<div v-if="userRole === 'admin'" class="admin-panel">
<h2>Admin Dashboard</h2>
<p>Full access to all features</p>
</div>
<div v-else-if="userRole === 'moderator'" class="moderator-panel">
<h2>Moderator Panel</h2>
<p>Limited administrative access</p>
</div>
<div v-else-if="userRole === 'user'" class="user-panel">
<h2>User Dashboard</h2>
<p>Standard user features</p>
</div>
<div v-else class="guest-panel">
<h2>Welcome Guest</h2>
<p>Please log in to access features</p>
</div>
<div v-if="isLoading">Loading...</div>
<div v-else-if="hasError">Error occurred</div>
<div v-else>{{ content }}</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
let userRole = ref('user')
let isLoading = ref(false)
let hasError = ref(false)
let content = ref('Welcome to the application!')
</script>
The v-else-if directive checks additional conditions when the previous v-if is false, while v-else provides fallback content when all conditions fail. These directives must be placed on consecutive elements with no other elements in between to form a proper conditional chain.
Best Practice Note:
This is the same conditional rendering approach we use in CoreUI Vue components for role-based interfaces. Keep conditional chains simple and consider using computed properties for complex condition logic to improve template readability.