Conditional Rendering


Reminder: Conditional statements

Conditional statements are used to perform different actions based on different conditions.

In all logical programming languages we do this using "if(statement to check)" :

If the result of the condition statement is true (boolean), then the code gets executed. There could also be an "else" statement that gets executed when the condition statement returns false. 

The condition statement could also be checking if a string is empty or not. This is very common for checking inputs and textareas. 


v-if and v-else

Vue has three directives to preform conditional rendering: v-if , v-show and v-else.

For the sake of learning let's assume(for now) v-if and v-show are the same things. 

Imagine there's this boolean variable (in a real application it's probably fetched via ajax) that tells us if the user is logged in or not:

new Vue({
el: '#app',
data: {
isLoggedIn: false
}
});

And a welcome heading that is different to logged in users and guests:

<h3 v-if="isLoggedIn">
Welcome dear user
</h3>
<h3 v-else>
Welcome Guest
</h3>

Result:

Welcome Guest

Example explained: 

The condition statement is checking if the "isLoggedIn" is initialized to true or false(v-if="isLoggedIn" is the same as v-if="isLoggedIn == true" ). As you can see we initialized it as false in our Vue instance; so it returns false and the code inside the v-if block does not get executed. 

Next, there is a v-else block which gets executed since v-if didn't. 


v-if vs v-show

In the manner of usage, v-show works exactly as v-if except one difference:

v-if conditionally loads something based upon your expression, whereas v-show just toggles the display. 

I suggest using v-show if you need to toggle something very often, and use v-if when the condition is unlikely to change at runtime.


v-show and v-model

Using v-show and v-model is very common in Vue applications when dealing with inputs and textareas. 

Lets assume we have a form, and we intend to show the submit button when the input is filled. Also, let's show a message letting user know they haven't filled the input yet. 

First lets initialize our model and name it "title": 

new Vue({
el: '#app',
data: {
title: null
}
});

And then set v-show on the submit button:

<form>
<p v-show="!title">
Please fill the title:
</p>
<input type="text" name="title" v-model="title">
<button type="submit" v-show="title">
Submit
</button>
</form>


Comments: