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.
Vue has three directives to preform conditional rendering:
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:
And a welcome heading that is different to logged in users and guests:
Welcome dear user
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.
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.
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":
And then set v-show on the submit button:
Please fill the title:
<input type="text" name="title" v-model="title">
<button type="submit" v-show="title">