One of the key features of Vue is its powerful directives, which simplify tasks like conditional rendering. If you’re familiar with frameworks like Angular or Laravel, Vue’s directives might feel familiar.
This article explores conditional rendering in Vue, specifically focusing on v-if, v-else, v-else-if, and v-show.
Setting Up a Vue Application
To begin, you’ll need a basic Vue.js setup. For this demonstration, we’ll use Vue 3 and the Composition API. Here’s a simple example:
<!DOCTYPE html><html><head> <title>Vue.js Tutorial</title> <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script></head><body><div id="app"> <!-- Content will go here --></div><script> const { createApp } = Vue; createApp({ // Vue setup will go here }).mount('#app');</script></body></html>
Using v-if, v-else, and v-else-if
Conditional rendering in Vue is similar to JavaScript’s if, else if, and else statements. Vue uses the v-if directive to evaluate conditions and render DOM elements accordingly.
Example: Checking User Status
Here’s an example where we check if a user is online of offline:
Initially, it will display the Online status with a green button. When the Change Status button is clicked, it will toggle between a red and green button. If the status is Online, a green button is displayed; otherwise, a red button is shown.
Using v-else-if
You can add more nuanced checks using v-else-if. For instance:
• If the user is “Online“ we will display a green button
• Otherwise, we will display a red button
We can go further and use v-if, v-else-if, and v-else. This is similar to if, else if, and else in programming languages. It randomly picks a status from Online, Offline, and Unknown.
Vue requires v-if, v-else, and v-else-if to be adjacent in the DOM. Introducing unrelated elements between them can break the logic and lead to errors.
Breaking v-if with p tag
Using v-show
Another directive, v-show, offers a similar outcome to v-if but operates differently. While v-if removes elements from the DOM when conditions aren’t met, v-show toggles their visibility using CSS’s display: none.
Example:
<div id="app"> <p v-show="true">Show this message</p> <p v-show="false">Don’t show this message</p></div>
• The first p tag will always be visible
• The second p tag will exist in the DOM but remain hidden
v-show example
Key Difference:
Use v-show when toggling visibility frequently and v-if when elements need to be dynamically added or removed to optimize performance.