How to use v-if in Vue
Conditional rendering with v-if is fundamental for creating dynamic Vue applications that show different content based on component state and user interactions. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented v-if directive in numerous Vue components for error states, loading indicators, user permissions, and responsive layouts in enterprise applications. From my expertise, the most effective approach is to use v-if with v-else and v-else-if for complete conditional logic. This method provides clean template syntax, efficient DOM manipulation, and proper component lifecycle management through Vue’s reactivity system.
Use v-if
directive with v-else
and v-else-if
for conditional rendering based on component state.
<template>
<div>
<div v-if="isLoading">Loading...</div>
<div v-else-if="error">Error: {{ error.message }}</div>
<div v-else-if="users.length === 0">No users found</div>
<div v-else>
<h2>Users List</h2>
<UserCard v-for="user in users" :key="user.id" :user="user" />
</div>
</div>
</template>
The v-if
directive conditionally renders elements based on the truthiness of expressions. When the condition is false, Vue completely removes the element from the DOM, which is different from v-show
that only toggles CSS visibility. Use v-else-if
for multiple conditions and v-else
for fallback content. These directives must be used on adjacent elements to form a conditional chain. Vue efficiently manages component lifecycle, calling appropriate hooks when elements are added or removed from the DOM.
Best Practice Note:
This is the same approach we use in CoreUI Vue components for dynamic content and state-based rendering.
Use v-if
when elements are toggled infrequently and v-show
for frequent toggles - v-if
has higher toggle costs but lower initial render cost, while v-show
has higher initial render cost but lower toggle costs.