JAVASCRIPT
Conditional Rendering with `v-if` vs. `v-show` in Vue 3
Master Vue 3's conditional rendering directives, `v-if`, `v-else-if`, `v-else`, and `v-show`, to efficiently control DOM element visibility based on data.
<template>
<div>
<h2>v-if Example</h2>
<button @click="toggleIf">Toggle v-if</button>
<p v-if="isVisibleIf">This paragraph appears/disappears (DOM mounted/unmounted) with v-if.</p>
<p v-else-if="isElseIf">This is the else-if block.</p>
<p v-else>This is the else block.</p>
<h2>v-show Example</h2>
<button @click="toggleShow">Toggle v-show</button>
<p v-show="isVisibleShow">This paragraph is always in the DOM, but its display is toggled with v-show.</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const isVisibleIf = ref(true);
const isElseIf = ref(false); // Example for else-if
const isVisibleShow = ref(true);
const toggleIf = () => {
isVisibleIf.value = !isVisibleIf.value;
// You can also toggle isElseIf here for a more complete v-if/else-if/else demo
};
const toggleShow = () => {
isVisibleShow.value = !isVisibleShow.value;
};
</script>
How it works: This snippet illustrates the two primary methods for conditional rendering in Vue 3: `v-if` and `v-show`. `v-if` conditionally renders elements by mounting or unmounting them from the DOM, making it suitable for elements that frequently toggle. `v-else-if` and `v-else` provide fallback content. In contrast, `v-show` always renders the element to the DOM and simply toggles its CSS `display` property, which is more efficient for elements that are toggled often but should remain in the DOM structure.