Conditional with VueJS

Posted by in Javascript and TypeScript

Let’s keep on learning VueJS, and now it is turn for conditionals in VueJS. Let’s learn how to use if … then, or if … else if … else …

the exercise is very easy, and inside the HTML code, We are using the directive v-if, v-else-if o v-else.

The target

Today’s exercise is to display two buttons, one for “Like” and another for “Do not like”, both controlled by like and notlike variables. If I ckick in one button,I will change the valeo of the property assigned. If True, it changes to False, and if it is False, it moves to True. Depending on the state, it will show a different message. Nothing realy complex.

In the second part of the exercise, I included the same code but using v-show.


<!DOCTYPE html>
<html>
<title>ManejandoDatos.es - VueJS Eventos</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="estilo.css" rel="stylesheet" />
<body>
	
<div id="main">
		
		<button v-on:click="like = !like">Me gusta - Like</button>
		<button @click="notlike = !notlike">No me gusta - Don't Like</button>
		
<h3 v-if="like">Me gusta!! :-)</h3>

<h3 v-else-if="notlike">No me gusta :-(</h3>

<h3 v-else>Upssss</h3>

<hr>

<h3 v-show="like">Me gusta!! :-)</h3>

<h3 v-show="notlike">No me gusta :-(</h3>

<h3 v-show="!notlike && !like">Upssss</h3>

</div>

</body>
</html>   
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script> <script> let app2 = new Vue({ el: '#main', data: { like: false, notlike: false } }) </script>

If I click on “Like”, it will show a message, but if I click on Don’t Like, it will show another different message, but if both variables are false, in the uper part it will show also a different message.

VueJS condicionales

VueJS condicionals

v-show only modifies the style

The both do the same, but what is the difference between v-show and v-if? Is it there any difference. The answer is yes. The only difference is that with v-show always keep the content in the DOM, although it will be visible or not depending on the style. In the previous image you can verify it.

So, depending if you need the DOm to be ready for showing some code or not, you can use this directiv v-show.

Easy, isn’t it? Go, go, go … with VueJS!