Showing and hiding elements (v-show directive)

Published on March 13, 2017 by

In the previous article, we took a look at the v-if, v-else-if and v-else directives. These directives add or remove elements from the DOM, depending on the evaluation of expressions. What I want to show you now, is a directive that shows or hides elements in the same fashion – namely the v-show directive. This directive works the same way as the v-if directive, except that the elements remain in the DOM and are only hidden by CSS.

I have prepared a simple example with two paragraphs and a button in the template. The Vue instance has an isNinja boolean data property which is switched when clicking the button. What I want to do, is to show the first paragraph if isNinja is true, and show the second paragraph if it is false.

To do that, I can simply enter the name of the data property in the v-show directive’s expression.

<p v-show="isNinja">Invisible like a ninja!</p>

I can do the same with the second paragraph, except that I will negate the boolean by prefixing an exclamation mark.

<span class="code"><p v-show="!isNinja">Here I am!</p></span>

Note that I could also have used more complex expressions here, but these ones are sufficient for this example.

Clicking the button now will switch from one paragraph to the other. If we take a look at the DOM through the browser’s developer tools, we can see that the paragraph that is not shown actually has a style of display: none. Clicking the button again, you can see that this style switches from one paragraph to the other, depending on which paragraph’s v-show expression that evaluates to false.

So as you can see, the v-show shows or hides elements unlike v-if which adds or removes elements.

Featured

Learn Vue.js today!

Take an online course and become an Vue.js champion!

Here is what you will learn:

  • How to build advanced Vue.js applications (including SPA)
  • How Vue.js works under the hood
  • Communicating with services through HTTP
  • Managing state of large applications with Vuex
  • ... and much more!
Vue.js logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

0 comments on »Showing and hiding elements (v-show directive)«

  1. Hamed

    Thanx bro
    It’s worked!

Leave a Reply

Your e-mail address will not be published.