Open In App

Vue.js Conditional Rendering

Last Updated : 11 Feb, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Vue.js is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries.

Conditional Rendering in Vue makes it easy to toggle the presence of any element in the DOM based on a certain condition. The directives v-if and v-else are used for this purpose. 

The v-if directive can be used to conditionally render a block. It can be assigned a boolean variable and based on the value it toggles the underlying DOM element. The v-else directive can be used to render a block that does not fulfill the condition of the v-if directive. This directive must immediately follow the v-if directive for it to work. The v-else-if directive can also be used to chain multiple conditionals.

The below examples demonstrate conditional rendering in Vue.js:

Example 1: In this example, the text given in the v-if directive will be shown if the isVisible variable is true.

Filename: index.html

HTML




<html>
<head>
  <script src=
  </script>
</head>
<body>
  <div id='parent'>
    <h1 style="color: green">
      GeeksforGeeks
    </h1>
    <strong v-if="isVisible">
      This text is visible!
    </strong>
  </div>
  <script src='app.js'></script>
</body>
</html>


Filename: app.js

Javascript




const parent = new Vue({
  el : '#parent',
  data : 
    
    // Data is interpolated
    // in the DOM
    isVisible: false
  }
})


Output:

Example 2:

Filename: index.html

HTML




<html>
<head>
  <script src=
  </script>
</head>
<body>
  <div id='parent'>
    <h1 style="color: green">
      GeeksforGeeks
    </h1>
    <h3>Data Structure Course</h3>
    <p v-if='gfg'>
      GeeksforGeeks Self paced Data Structure
      course is Awesome!
    </p>
  
    <p v-else>
      Not GeeksforGeeks course!
    </p>
  
  </div>
  <script src='app.js'></script>
</body>
</html>


Filename: app.js

Javascript




const parent = new Vue({
  el : '#parent',
  data : {
    
    // Data is interpolated
    // in the DOM
    gfg: true
  }
})


Output:

  • When the gfg variable is set to true

  • When the gfg variable is set to false



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads