How to Use v-if in Vue: Conditional Rendering Explained
In Vue, use the
v-if directive to conditionally render elements based on a JavaScript expression. If the expression is true, the element appears in the DOM; if false, it is removed. This helps control what users see dynamically.Syntax
The v-if directive is added to an HTML element followed by a JavaScript expression inside quotes. Vue evaluates this expression to decide if the element should be rendered.
- v-if: The directive that controls conditional rendering.
- Expression: A JavaScript condition that returns true or false.
vue
<div v-if="isVisible">This text shows only if isVisible is true.</div>
Output
This text shows only if isVisible is true.
Example
This example shows a button that toggles a message. The message only appears when the showMessage data property is true, demonstrating how v-if controls visibility.
vue
<template>
<div>
<button @click="showMessage = !showMessage">
Toggle Message
</button>
<p v-if="showMessage">Hello! You can see me now.</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const showMessage = ref(false)
</script>Output
Button labeled 'Toggle Message' and no message initially. Clicking the button shows or hides the text 'Hello! You can see me now.'
Common Pitfalls
Common mistakes when using v-if include:
- Using
v-ifandv-showinterchangeably without knowing the difference:v-ifadds/removes elements,v-showonly toggles visibility. - Placing
v-ifon parent elements unintentionally removing child components. - Using complex expressions inside
v-ifthat are hard to read or debug.
vue
<!-- Wrong: Using v-if and v-show together on same element --> <p v-if="isVisible" v-show="isVisible">This is redundant and inefficient.</p> <!-- Right: Use only one directive based on need --> <p v-if="isVisible">Rendered only when true.</p>
Output
The first paragraph is inefficient and may cause confusion; the second paragraph correctly uses v-if alone.
Quick Reference
| Directive | Purpose | Behavior |
|---|---|---|
| v-if | Conditionally render element | Adds/removes element from DOM based on expression |
| v-else | Render element if previous v-if is false | Works only after v-if or v-else-if |
| v-else-if | Chain multiple conditions | Acts like else if in JavaScript |
| v-show | Toggle element visibility | Element always in DOM, toggles CSS display |
Key Takeaways
Use
v-if to add or remove elements based on a condition.The expression inside
v-if must return true or false.Avoid mixing
v-if and v-show on the same element.Use
v-else and v-else-if to handle multiple conditions.Remember
v-if removes elements from the DOM, which can affect performance if toggled frequently.