0
0
Vueframework~5 mins

v-show vs v-if difference in Vue

Choose your learning style9 modes available
Introduction

We use v-show and v-if to control if something appears on the page or not. They help us show or hide parts of the page easily.

When you want to quickly hide or show something without removing it from the page.
When you want to completely add or remove something from the page based on a condition.
When you want better performance for toggling visibility many times.
When you want to save resources by not rendering something until needed.
Syntax
Vue
<div v-if="condition">Content</div>
<div v-show="condition">Content</div>

v-if adds or removes the element from the page.

v-show keeps the element but hides it with CSS display: none.

Examples
This element only exists in the page if isVisible is true.
Vue
<div v-if="isVisible">Hello with v-if</div>
This element is always in the page but hidden if isVisible is false.
Vue
<div v-show="isVisible">Hello with v-show</div>
Sample Program

Clicking the button toggles both paragraphs. The v-if paragraph is added or removed from the page. The v-show paragraph stays but is hidden or shown.

Vue
<template>
  <button @click="toggle">Toggle</button>
  <p v-if="showIf">This is shown with v-if</p>
  <p v-show="showShow">This is shown with v-show</p>
</template>

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

const showIf = ref(true)
const showShow = ref(true)

function toggle() {
  showIf.value = !showIf.value
  showShow.value = !showShow.value
}
</script>
OutputSuccess
Important Notes

v-if is better when you want to avoid rendering until needed.

v-show is better for frequent toggling because it only changes CSS.

Use v-if if the element is heavy or complex to render.

Summary

v-if adds or removes elements from the DOM.

v-show toggles visibility using CSS but keeps elements in the DOM.

Choose based on how often you toggle and performance needs.