Vue v-if Directive

Vue Tutorial

🔀 Vue v-if Directive

In Vue.js, the Vue v-if Directive is used for conditional rendering.

It adds or removes elements from the DOM based on a condition.


 What is Vue v-if Directive?

v-if renders an element only if the condition is true.

<p v-if="isLogin">Welcome User</p>

If isLogin is:

  • true → element is shown

  • false → element is removed from the DOM


 Basic Example

<div id="app">
<h2 v-if="age >= 18">You are eligible to vote</h2>
</div>
<script>
const app = Vue.createApp({
data() {
return {
age: 20
}
}
})
app.mount(“#app”)
</script>

v-if with v-else

Used when you want two conditions.

<p v-if="isLoggedIn">Dashboard</p>
<p v-else>Please Login</p>

📌 v-else must be immediately after v-if.


v-if with v-else-if

Used for multiple conditions.

<p v-if="marks >= 75">Distinction</p>
<p v-else-if="marks >= 50">Pass</p>
<p v-else>Fail</p>

 Using v-if with <template>

When you need to conditionally render multiple elements.

<template v-if="isAdmin">
<h3>Admin Panel</h3>
<p>Welcome Admin</p>
</template>

📌 <template> does not appear in the DOM.


v-if vs v-show

Feature v-if v-show
DOM Handling Adds/Removes element Uses display: none
Initial Render Slower Faster
Toggle Cost Lower Higher
Use Case Rare condition changes Frequent toggling

✔ Use v-if when condition changes rarely
✔ Use v-show when toggling often


v-if with Boolean Expressions

<p v-if="isActive && isVerified">
Account Verified
</p>

 Common Mistakes ❌

❌ Using v-if and v-for together

<li v-for="item in items" v-if="item.active">...</li>

✔ Correct way:

<li v-for="item in activeItems" :key="item.id">...</li>

 Key Points to Remember

  • v-if removes elements from DOM

  • Works with:

    • v-else

    • v-else-if

  • Use <template> for multiple elements

  • Better for conditional rendering logic


 Conclusion

The v-if directive is essential for controlling what appears on the screen in a Vue app.
Understanding v-if helps you build clean, efficient, and optimized UIs.

You may also like...