Conditional Rendering/Display in Vue with v-if, v-show, v-else and v-else-if

Introduction

Vue.js is a simple web app framework for creating dynamic web interfaces and Single-Page Apps (SPAs). As we create these apps, oftentimes, we want to render something based on a particular criteria - this is the essence of conditional rendering.

Conditional rendering refers to the ability to render distinct user interface (UI) markup based on whether a condition is true or not. This notion is frequently used in contexts like showing or hiding components (toggling), switching application functionality, handling authentication and authorization, and many more.

In this article, we'll look at various ways of conditionally rendering in Vue.js by using the v-if, v-else-if, and v-else directives. We will also take a look at some examples and highlight the difference between the v-if and v-show.

v-if

The v-if directive is used to conditionally render a block meaning the block with the v-if attribute will only be produced if the directive's expression returns a true value. If the expression produces an invalid result (for example, null, 0, empty string, false), the element is deleted from the DOM.

Let's illustrate this behavior on the practical example:

<div v-if="login">
    <p>This user has been logged in!... Welcome.</p>
</div>

<script>
export default {
    data() {
        return {
            login: true,
        };
    }
};
</script>

Since login is set to true, the <div> block containing v-if directive will be produced, thus displayed.

v-if vs v-show

It is worth noting that the v-show would also work in the example above and would function seemingly identically, but there is a distinction between the two.

v-if conditionally renders an element, whereas v-show conditionally shows/displays an element.

This implies that when the conditional is toggled, v-if will actually delete and restore components wile v-show just makes them invisible or visible. The following animation illustrates how v-if actually deletes and reproduces code blocks:

Meanwhile, v-show will always maintain the element in the DOM and will just change its CSS to toggle its appearance (by setting its display to none):

v-else

The v-else directive is a v-if directive that allows you to customize the false value in conditional renderings. If it isn't true, you can use v-else to define what should happen instead.

For example, assume we have a password input, and we want it to produce an error message, "Weak Password", if the length of the input is less than 6 or display "Strong Password" if the length is greater than 6.

This is a conditional render, with an option for handling the false-case:

<form>
    <input type="password" v-model="password" placeholder="Enter your password" />
    <p v-if="password.length > 6">Strong Password</p>
    <p v-else>Weak Password</p>
</form>

<script>
export default {
    data() {
        return {
            password: ""
        };
    }
};
</script>

Note: v-if/v-else works like the regular if and if...else expression in JavaScript.

Let's utilize this to toggle contents of a simple login page so it changes the message based on whether a user is logged in or not. We'll modify the button wording based on the userLoggedIn status as well:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

<div id="app">
    <div v-if="userLoggedIn">
        <h2>Hello Welcome!</h2>
        <p>You have sucessfully logged in to your user account!</p>
    </div>
    <div v-else>
        <p>Please Log In to access your account!</p>
    </div>
    <button @click="userLoggedIn = !userLoggedIn">
        <p v-if="!userLoggedIn">Login</p>
        <p v-else>LogOut</p>
    </button>
</div>
    
<script>
export default {
    data() {
        return {
            userLoggedIn: false
        };
    }
};
</script>

The button’s click event will toggle the userLoggedIn data item, and this will affect the data displayed as seen below:

v-else-if

v-else-if extends a v-if with an else...if block. This is similar to JavaScript's else...if block in that it allows us to add an if statement to an existing v-if. This is used when there are many criteria to check and can be chained several times:

<form>
    <input type="password" v-model="password" placeholder="Enter your password" />
    <p v-if="password.length < 4">Weak Password</p>
    <p v-else-if="password.length < 7">Fairly Strong Password</p>
    <p v-else>Strong Password</p>
</form>

<script>
export default {
    data() {
        return {
            password: ""
        };
    }
};
</script>

Note: When both v-if and v-for are used to the same element, v-if is evaluated first. This simply implies that using v-if and v-for on the same element is not advised, owing to implicit precedence.

Conclusion

In this article, we've seen how to conditionally render an element with v-if, v-else, and v-else-if. We also explained the difference between v-if and v-show.

Last Updated: June 15th, 2022
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms