My Journey

Conditional Rendering in Vue.js

January 05, 2020

🗣If you’re following my blog posts, you already know that for the past few weeks I am exploring Vue.js and along with it I am also documenting my journey. So, today’s post is about conditional rendering in Vue.js.

🔎 v-if and v-else:

Let’s understand this with an example that we have two elements and we want to show the first element only if the condition is true and the second element when the condition is false.

<div id="explore">
 <span v-if="seen">In v-if element</span> //will be added to DOM as the condition is true
 <span v-else> In v-else element </span> 
</div> 
var app = new Vue({
 el: '#explore',
 data() {
   return {
       seen: true
   }
 }
})

As the seen property is set to true, so the first element will be rendered and the second element element will will be ignored. But if we set the seen to false,

<div id="explore">
  <span v-if="seen">In v-if element</span> 
  <span v-else> In v-else element </span> //will be added to DOM as the condition is false
</div> 
var app = new Vue({
 el: '#explore',
 data() {
   return {
       seen: false
   }
 }
})

Now the first element will be ignored as the condition is not met and the v-else element will be added to DOM. When using the v-else it’s important to remember that it comes immediately after the element with v-if directive.


Zahid Jabbar

📝 Thoughts by Zahid Jabbar.
Who aspires to be a full-stack developer.