0
0
VueHow-ToBeginner · 3 min read

How to Use v-show in Vue: Simple Visibility Control

Use the v-show directive in Vue to toggle an element's visibility by changing its CSS display property. Bind v-show to a boolean expression; when true, the element is visible, and when false, it is hidden but still in the DOM.
📐

Syntax

The v-show directive is used as an attribute on an HTML element. It takes a boolean expression that controls the element's visibility.

  • v-show="condition": Shows the element if condition is true.
  • The element remains in the DOM regardless of the condition.
  • Visibility is controlled by toggling the CSS display property.
vue
<div v-show="isVisible">This text is visible when <code>isVisible</code> is true.</div>
💻

Example

This example shows a button that toggles the visibility of a message using v-show. The message stays in the DOM but appears or disappears visually.

vue
<template>
  <div>
    <button @click="toggle">Toggle Message</button>
    <p v-show="isVisible">Hello! You can see me when visible.</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const isVisible = ref(true)
function toggle() {
  isVisible.value = !isVisible.value
}
</script>
Output
A button labeled 'Toggle Message' and a paragraph 'Hello! You can see me when visible.' that appears and disappears when the button is clicked.
⚠️

Common Pitfalls

Common mistakes when using v-show include:

  • Expecting v-show to remove the element from the DOM (it only hides it).
  • Using v-show when you want to conditionally render elements (use v-if instead).
  • Not initializing the bound variable as a boolean, which can cause unexpected behavior.
vue
<!-- Wrong: expecting element removal -->
<div v-show="false">This is hidden but still in DOM.</div>

<!-- Right: use v-if to remove from DOM -->
<div v-if="false">This is removed from DOM.</div>
📊

Quick Reference

Featurev-showv-if
DOM PresenceAlways in DOMAdded/removed from DOM
Visibility ControlCSS display toggledElement rendered or not
PerformanceBetter for frequent togglesBetter for conditional rendering
Use CaseToggle visibility without re-renderRender conditionally

Key Takeaways

Use v-show to toggle element visibility by changing CSS display without removing it from the DOM.
Bind v-show to a boolean reactive variable for dynamic control.
Use v-if instead if you want to add or remove elements from the DOM.
Initialize the controlling variable as a boolean to avoid unexpected results.
Choose v-show for frequent toggling and v-if for conditional rendering.