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.
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!