How does v-if work?
v-if is a Vue directive for conditional rendering that adds or removes an element from the DOM depending on an expression.
In simpler terms:
If the condition is true, the element is created and inserted into the DOM. If it is false, the element is removed completely.
How v-if works
Example:
<p v-if="isVisible">Hello!</p>If isVisible = true → Vue creates the element
If isVisible = false → the element is removed
v-if, v-else-if, v-else
<div v-if="status === 'success'">Success</div>
<div v-else-if="status === 'error'">Error</div>
<div v-else>Unknown</div>The lifecycle of v-if
When the condition changes:
- If it switches to true, Vue creates a new DOM element and runs all the hooks (mounted, updated, etc.).
- If it switches to false, Vue removes the element from the DOM, calling the unmounted hooks.
This matters at interviews.
Important nuances
1. v-if is used for rarely displayed elements
For example, modals, heavy lists, complex blocks.
Because every time the element is created and destroyed → this is more costly.
2. v-if cannot be used with v-for on the same element (Vue 3)
Not allowed:
<div v-for="item in items" v-if="item.visible"></div>But allowed:
<template v-for="item in items">
<div v-if="item.visible">{{ item.name }}</div>
</template>Or filter the data beforehand.
3. Grouping through <template>
<template v-if="show">
<h1>Title</h1>
<p>Text</p>
</template><template> is not rendered into the DOM, only its contents are.
4. Differences from v-show
v-if | v-show |
|---|---|
| completely removes/creates the node | just hides it through display: none |
| more expensive on frequent toggles | more expensive on first render |
| suited for rarely displayed content | suited for frequent toggling |
Example with animation (transition + v-if)
Vue understands enter/leave transitions:
<transition>
<p v-if="visible">Hello!</p>
</transition>When visible changes, Vue runs the CSS animation for appearing or disappearing.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.