v-show
There's a second directive for showing and hiding: v-show. It's written just like v-if:
<script setup>
import { ref } from "vue";
const showHours = ref(false);
</script>
<template>
<button @click="showHours = !showHours">Opening hours</button>
<p v-show="showHours">Every day from 7 am to 7 pm.</p>
</template>But it works differently. The element is always on the page, and v-show only hides it, with the CSS display: none. Before the first click, the page has:
<button>Opening hours</button>
<p style="display: none;">Every day from 7 am to 7 pm.</p>A click only changes the paragraph's style. With v-if, the paragraph wouldn't be on the page at all, only a comment that marks its place, <!--v-if-->, and each click would make the paragraph anew or remove it.
Which one should you use? Mostly v-if. v-show is for something that's shown and hidden often, such as a menu that opens and closes: changing a style is quicker than making the element again. But there's no v-else for v-show, and a hidden element is still rendered, even if nobody ever looks at it.
Instructions
- 1
Hide the list of allergens with
v-showuntil the button is clicked. Each click on the button switchesshowAllergensto the opposite, so that the list shows and hides. - 2
Make the button say Hide allergens while the list is shown, and Show allergens while it's hidden.