Conditional Rendering (v-if vs v-show)

💚 Vue.js Lesson 5 Beginner

Conditional rendering allows you to toggle elements on or off. Vue provides two main directives for this: v-if and v-show, which operate differently under the hood.

1 v-if vs v-show

The difference lies in how elements are rendered:

  • v-if: True conditional rendering. It physically adds or removes elements from the DOM. If the condition is initially false, it does not render the element at all. It also supports v-else-if and v-else blocks.
  • v-show: Much simpler. It always renders the element in the DOM, toggling its visibility using the CSS display: none; property.
  • Performance: v-if has higher toggle costs (requires re-building the DOM), while v-show has higher initial render costs. Use v-show for elements that need to be toggled frequently.
2 Conditional Directives in Template

Let's check how to use conditional directives in a template:

HTML — Vue Conditionals
<!-- Using v-if / v-else-if / v-else -->
<div v-if="user.role === 'admin'">
  <p>Welcome, Administrator.</p>
</div>
<div v-else-if="user.role === 'editor'">
  <p>Welcome, Content Editor.</p>
</div>
<div v-else>
  <p>Welcome, Guest User.</p>
</div>

<!-- Using v-show for frequent toggles -->
<div v-show="isNotificationPanelOpen" class="popout-panel">
  <p>You have 3 new notifications.</p>
</div>
3 Code Challenge
Challenge: Write a component containing an input field and a toggle button. Use v-if to display a warning message only when the input field value length exceeds 10 characters.