Difference between v-if and v-show in Vue.js
Zahid Jabbar
Posted on January 14, 2020
π 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>
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-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.
π€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.
Posted on January 14, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.