Vue3 v-show Directive
v-showThe directive is used to toggle an element's visibility based on the truthy/falsy value of an expression. It controls the element's display and hiding through the CSS display property.
Basic Explanation
v-showThe directive determines whether an element is displayed based on the truthy/falsy value of the bound expression. Regardless of whether the condition is true or false, the element is rendered to the DOM, and its visibility is controlled via CSS.
- Expected Type: any
- Effect: Toggles the element's visibility based on the truthy/falsy value of the expression, controlled by the CSS display property.
Difference between v-show and v-if
| Feature | v-show | v-if |
|---|---|---|
| Rendering method | Always rendered to the DOM, only controls show/hide | Renders when condition is true, does not render when false |
| Toggle performance | Low toggling overhead (only changes CSS) | High toggling overhead (requires creating/destroying elements) |
Usage Scenarios
1. Frequently toggling display state
When an element needs to be shown/hidden frequently, using v-show provides better performance:
Example
<template>
<div>
<button @click="showModal = true">Open popup</button>
<div class="modal" v-show="showModal" @click="showModal = false">
<div class="modal-content" @click.stop>
<p>This is a popup</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return { showModal: false }
}
}
</script>
<div>
<button @click="showModal = true">Open popup</button>
<div class="modal" v-show="showModal" @click="showModal = false">
<div class="modal-content" @click.stop>
<p>This is a popup</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return { showModal: false }
}
}
</script>
Other extensions
Vue3 Built-in Directives