DEV Community

Zahid Jabbar
Zahid Jabbar

Posted on

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

πŸ” v-if and v-show are Vue.js directives and they are used to show the information depending upon certain conditions that are defined by the user

πŸ‘‰ 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>

Enter fullscreen mode Exit fullscreen mode
var app = new Vue({
  el: '#app',
  data() {
    return {show: false}
  }
})
Enter fullscreen mode Exit fullscreen mode

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-show

<div id="app">
  <span v-show="show">Learning about v-show</span>
</div>

Enter fullscreen mode Exit fullscreen mode
var app = new Vue({
  el: '#app',
  data() {
    return {show: false}
  }
})
Enter fullscreen mode Exit fullscreen mode

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.

πŸ€”Which to use?

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 there is not much work to do, so it's more performant.

Latest comments (0)