0
0
VueHow-ToBeginner · 3 min read

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-if and v-show interchangeably without knowing the difference: v-if adds/removes elements, v-show only toggles visibility.
  • Placing v-if on parent elements unintentionally removing child components.
  • Using complex expressions inside v-if that 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

DirectivePurposeBehavior
v-ifConditionally render elementAdds/removes element from DOM based on expression
v-elseRender element if previous v-if is falseWorks only after v-if or v-else-if
v-else-ifChain multiple conditionsActs like else if in JavaScript
v-showToggle element visibilityElement 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.