Vue.js Conditional Rendering

Vue.js provides built-in directives to conditionally render elements in the DOM. This functionality allows you to show or hide parts of the UI based on your application's data without manually manipulating the DOM.



What is Conditional Rendering?

Vue offers several directives for conditional rendering:

  • v-if
  • v-else-if
  • v-else
  • v-show

These directives let you control what appears on the page depending on dynamic conditions.

Using v-if

The v-if directive conditionally includes or removes an element from the DOM.

<div id="app">
  <p v-if="loggedIn">Welcome back!</p>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      loggedIn: true
    }
  });
</script>

In this example, the paragraph is rendered only if loggedIn is true.

Using v-else-if and v-else

You can chain conditions using v-else-if and v-else after a v-if block. This works like if...else if...else in JavaScript.

<div id="app">
  <p v-if="score >= 90">Grade: A</p>
  <p v-else-if="score >= 75">Grade: B</p>
  <p v-else>Grade: C</p>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      score: 82
    }
  });
</script>

In this example, only one of the three elements is rendered, depending on the value of score.

Using v-show

The v-show directive toggles an element's visibility using CSS (display: none) but does not remove the element from the DOM.

<div id="app">
  <p v-show="visible">This text is visible.</p>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      visible: true
    }
  });
</script>

In this example, the paragraph remains in the DOM and is shown or hidden based on the visible value.

Difference Between v-if and v-show

Feature v-if v-show
DOM behavior Adds or removes element entirely Toggles visibility using CSS
Performance Better for rarely toggled content Better for frequent toggling
Initial render May delay rendering Always rendered initially

Use v-if when conditions rarely change. Use v-show when toggling visibility frequently.

Conclusion

In this tutorial, you learned how to conditionally render elements in Vue.js using v-if, v-else-if, v-else, and v-show. You saw how to control the presence and visibility of elements based on application data. These directives allow you to manage dynamic content efficiently and keep your templates clean and organized.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram