Let's move further and see how we use VueJS Conditional directives to show/hide elements in our DOM.

Problem: You want to show/hide an element depending on VueJS data property.

Solution: For this let's consider a very basic VueJS Instance which only has a single data property named count, and depending on the value of count we'll show or hide the element in the dom.

    var app = new Vue({
        el: '#app',
        data: {
            count: 10
        }
    });

#1 v-if and v-else conditionals

Now on our HTML page, we want to show or hide an element depending upon the value of count property. If the value is greater than 10, equal to 10 or less than 10. For this, we will utilize the v-if , v-else-if and v-else directives of VueJS.

<div id="app">
        <div v-if="count > 10">
            Count is greater than 10
        </div>
        <div v-else-if="count == 10">
            Count is 10
        </div>
        <div v-else>
            Count is less than 10
        </div>
    </div>

Try changing the value of count in the developer console or using Vue.js devTools Chrome Extension. You show to see the text on the screen changing depending upon the count value.

The important thing to note with the v-if and v-else directive is that it completely removes the element from the DOM instead of hiding it. Thus if you inspect the element using the inspect element option in your browser then you should see only one of the div in the DOM.

v-if and v-else directive in VueJS

 

#2 v-show

As a second option of showing or hiding elements on the HTML page, we can also make use v-show directive provided by VueJS

      <h3> Using v-show directive</h3>
        <div v-show="count > 10">
            Count is greater than 10
        </div>
        <div v-show="count == 10">
            Count is 10
        </div>
        <div v-show="count < 10">
            Count is less than 10
        </div>

Try changing the value of count in the developer console or using Vue.js devTools Chrome Extension. You show to see the text on the screen changing depending upon the count value.

The important thing to note with the v-show directive is that it keeps the element in the DOM and utilizes the CSS display property to show or hide the elements on the page.

v-show directive VueJS

Talking about the choice between the two and about performance, if the element requires frequent toggling then choose v-show instead of v-if

v-show: expensive initial load, cheap toggling,
v-if: cheap initial load, expensive toggling.

Read more in vue.js official documentation about v-if vs v-show.

Comments