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 ifconditionis true.- The element remains in the DOM regardless of the condition.
- Visibility is controlled by toggling the CSS
displayproperty.
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-showto remove the element from the DOM (it only hides it). - Using
v-showwhen you want to conditionally render elements (usev-ifinstead). - 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
| Feature | v-show | v-if |
|---|---|---|
| DOM Presence | Always in DOM | Added/removed from DOM |
| Visibility Control | CSS display toggled | Element rendered or not |
| Performance | Better for frequent toggles | Better for conditional rendering |
| Use Case | Toggle visibility without re-render | Render 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.