Saturday, December 28, 2024
Google search engine
HomeLanguagesJavascriptVue.js Conditional Rendering

Vue.js Conditional Rendering

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">
      neveropen
    </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">
      neveropen
    </h1>
    <h3>Data Structure Course</h3>
    <p v-if='gfg'>
      neveropen Self paced Data Structure
      course is Awesome!
    </p>
  
    <p v-else>
      Not neveropen 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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments