Introduction to Conditional Rendering

Conditional rendering in Vue.js allows you to show or hide elements in the DOM based on specified conditions. Vue.js provides the `v-if` and `v-else` directives for this purpose. In this guide, we'll explore how to use these directives for conditional rendering.


Using v-if Directive

The `v-if` directive is used to conditionally render an element if a given expression evaluates to true. If the expression is false, the element will not be included in the DOM. Here's an example:


<div id="app">
<p v-if="showMessage">This message is displayed.</p>
</div>
<script>
new Vue({
el: '#app',
data: {
showMessage: true
}
});
</script>

In this example, the paragraph is only rendered if the `showMessage` data property is true.


Using v-else Directive

The `v-else` directive is used in combination with `v-if` to conditionally render content when the `v-if` condition is false. Here's an example:


<div id="app">
<p v-if="showMessage">This message is displayed.</p>
<p v-else>This message is hidden.</p>
</div>
<script>
new Vue({
el: '#app',
data: {
showMessage: false
}
});
</script>

In this example, the first paragraph is rendered when `showMessage` is true, and the second paragraph is rendered when it's false.


Conclusion

Conditional rendering with `v-if` and `v-else` in Vue.js is a powerful feature that allows you to control what content is displayed based on specific conditions. It's essential for building dynamic and responsive user interfaces in your Vue.js applications.