iTranslated by AI
[Vue 3] What is v-show? A Guide to Its Usage
v-show is a directive (a Vue-specific attribute) used to conditionally display HTML (DOM) elements.
Usage
Here is how to use it. This works in Vue 3.
Basics
<script setup>
let isView = true
</script>
<template>
<p v-show="isView">v-show example</p>
</template>
The display is determined by true or false.
- Displays when true
- Hides when false
You can toggle the display dynamically using JavaScript.
v-show toggles the display using the CSS display property.
How it is written in Vue:
<p v-show="isView">v-show example</p>
The actual HTML:
<p style="display: none;">v-show example</p>
You can see that the CSS is added inline to the p tag.
Handling multiple elements with v-show
To toggle multiple elements, wrap them in a div or similar container and use v-show on it.
<template>
<h1>Page Title</h1>
<div v-show="isView">
<p>ev-show example</p>
<p>This Page is v-show example page</p>
</div>
</template>
Multiple conditions for v-show
You can also handle conditions, such as:
- When multiple conditions are true
- When either condition is true
This works the same way as if statements in JavaScript.
<script setup>
let isView = true
let isShow = true
</script>
<template>
<p v-show="isView && isShow">ev-show example</p>
</template>
<script setup>
let isView = false
let isShow = true
</script>
<template>
<p v-show="isView || isShow">ev-show example</p>
</template>
Differences between v-if and v-show
v-if is another directive with similar functionality. Here is the difference:
With v-if:
- It actually renders or removes the DOM element.
With v-show:
- The DOM is always rendered, and it toggles display using CSS.
Because v-if performs DOM operations during toggling, it takes more time, whereas v-show renders even the DOM that isn't displayed, which can result in a longer initial load time.
I have summarized my insights from 2.5 years of daily home-based development! Please take a look if you're interested.
Discussion