The v-show directive in Vue.js is used to conditionally display elements based on a boolean expression. Unlike v-if, which completely removes elements from the DOM when the condition is false, v-show toggles the CSS display property, keeping the element in the DOM but hiding it visually. This makes v-show more efficient when elements need to be frequently shown or hidden without re-rendering. It is best suited for UI toggles, such as modals, dropdowns, or tooltips.
The syntax is simple: isVisible controls the visibility of the element dynamically
<div v-show="isVisible">Content</div>
<template>
<div>
<button @click="isVisible = !isVisible">
Toggle Message
</button>
<p v-show="isVisible">Hello, Vue.js!</p>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: true
};
}
};
</script>
Explanation:
Both, v-if and v-show are conditional rendering, but unlike v-if, the v-show directive only make the object of concern invisible, for it is yet hidden part of the HTML-DOM.
| Feature | v-if | v-show |
|---|---|---|
| DOM Behavior | Completely adds/removes elements from the DOM | Only toggles the display property (keeps elements in the DOM) |
| Performance | Better for infrequent changes (expensive re-rendering) | Better for frequent toggling (faster updates) |
| Usage Case | When elements are rarely shown/hidden | When elements need to be toggled frequently |