My Journey

Difference between v-if and v-show in Vue.js

January 07, 2020

🔍 v-if and v-show are Vue.js directives and they are used to show the information conditionally and both have similar usage but different rendering costs.

👉 In case you’re not familiar with Vue.js directives, they are just like HTML attributes but they’re always prefixed with v- which is the indication that they’re special attributes provided by Vue.js. They apply reactive behavior to DOM.

👨‍💻 Let’s learn the difference between two with some code:

v-if

Let’s suppose we have this piece of code

<div id="app">
  <span v-if="show">Learning about v-if</span>
</div>
var app = new Vue({
  el: '#app',
  data() {
    return {
        show: false
    }
  }
})

In the v-if case, the element will only be rendered and inserted into DOM if the condition is true. If the condition is false and we check the DOM elements in the browser we’ll notice that there is no element. But as we turn the condition to true, it’s added to DOM. So, each time, depending upon the condition, there are DOM manipulations. v-if ensures that elements inside a the conditional block are destroyed and recreated depending upon the truthinees of the directive’s expression.

v-show

<div id="app">
  <span v-show="show">Learning about v-show</span>
</div>
var app = new Vue({
  el: '#app',
  data() {
    return {show: false}
  }
})

The element With v-show will always be rendered and it is present in the DOM but the CSS property Display: none will be toggled by v-show depending upon the condition.

🤔Conclusion?

There are different use cases for both. As we’ve learned that with v-if the element unmount and remount depending upon the condition and there is so much work to do for DOM manipulations. But with v-show it just stays in the DOM and as it just toggles the display property so there is not much work to do and it’s more performant, so it’s preferred to use v-show.


📝 Thoughts by Zahid Jabbar.
A developer.

👋 Say hi