Displaying and hiding an element conditionally in Vue.js

Displaying and hiding an element on a web page is fundamental to some designs. You could have a popup, a set of elements that you want to display one at a time, or something that shows only when you click on a button.

In this article, we will use conditional display and learn about the important v-if and v-show directives.

Before venturing into this article, ensure that you know enough about computed properties.

Let’s Get Started

Let’s build a ghost that is only visible at night:

<div id="ghost"> 
  <div v-show="isNight"> 
    I'm a ghost!
  </div> 
</div>

The v-show guarantees that the <div> ghost will be displayed only when isNight is true. For example:

new Vue({ 
  el: '#ghost', 
  data: { 
    isNight: true 
  } 
})

This will make the ghost visible. To make the example more real, we can write isNight as a computed property:

new Vue({ 
    el: '#ghost', 
    computed: { 
      isNight () { 
        return new Date().getHours() < 7 
    } 
  } 
})

If you load this program in JSFiddle, you will see the ghost only after midnight and before 7:00. If you really can’t wait to see the ghost, you can cheat and insert a time in the night, for example:

return (new Date('6 January 02:15')).getHours() < 7

How the above code works

The v-show directive evaluates the isNight computed property and puts a display: none in the element style attribute.

This means that the element is completely rendered by Vue; it’s just invisible, like a ghost.

The other directive for displaying elements conditionally is the v-if directive. The behavior is the same as that of v-show except that you won’t find the element in the DOM at all. When v-if evaluates to true, the element will be added dynamically, no element styling involved. To try it, just replace the v-show with v-if:

<div id="ghost"> 
  <div v-if="isNight"> 
    I'm a ghost! Boo! 
  </div> 
</div>

In general, if it makes no difference, using v-show is better because it requires fewer resources in the long run. On the other hand, if you are not even sure that some elements will appear on the page, using v-if will let your users save some CPU time (you never know when your app will go viral and have millions of users; you can save a lot of energy by choosing the right one!).

On a side note, don’t wait in front of the page until midnight. Nothing will happen. Computed properties are re-evaluated only when reactive properties inside them change. In this case, we have a Date that is not reactive and, thus, will not trigger any update.

Muhammad Mubeen

Muhammad Mubeen

Mubeen is a full-stack web & mobile app developer who is very proficient in MEAN.js, Vue, Python, Ionic 4, Flutter, Firebase, ROR, and PHP. He has created multiple mobile and web applications. He is very passionate about sharing his knowledge.

Leave a Reply

Your email address will not be published. Required fields are marked *

Trending