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


 


v-if with v-else

Used when you want two conditions.

v-else must be immediately after v-if.


v-if with v-else-if

Used for multiple conditions.


 Using v-if with <template>

When you need to conditionally render multiple elements.

<template> does not appear in the DOM.


v-if vs v-show

Featurev-ifv-show
DOM HandlingAdds/Removes elementUses display: none
Initial RenderSlowerFaster
Toggle CostLowerHigher
Use CaseRare condition changesFrequent toggling

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


v-if with Boolean Expressions


 Common Mistakes

 Using v-if and v-for together

 Correct way:


 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...