Vue.js: a quick start guide for beginners. Part 3

Vue.js: a quick start guide for beginners. Part 3
by Janeth Kent Date: 25-02-2019 javascript vueJs tutorial guide


Welcome here again! Last time we didn't listen to our very first user events and and methods to react to these events. Now we are going to explain directives and conditional rendering.

if-else

Regardless of the framework, one of the most important tools under any programmer's belt is conditional rendering. Depending on a condition or value, the ability to display or hide parts of your app is a great place to learn about this and also about Vue directives.

We'll continue to develop on our previous example.

<html>      
<head>          
<title>Vue 101</title>      
</head>        
<body>          
<h1>Hello!</h1>          
<div id="app">            
<p>My local property: {{ myLocalProperty }}</p>            
<hr>            
<button @click="buttonClicked">Click me</button>          
</div>            
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>            
<script>            
const app = new Vue({              
el: '#app',              
data: {                
myLocalProperty: 'Im a local property value'              
},              
methods: {                
buttonClicked() {                  
const newText = 'The new value is: ' + Math.floor( Math.random() * 100 );                    
this.myLocalProperty = newText;                
}              
}            
});         
</script>      
</body>  
</html>

So far, we have been able to display our local properties in our app and listen to a user's clicks on a simple button. Let's go a step further and find out about our conditional rendering.

Let's go a step further and find out about our conditional rendering. Let's change our button clicks to generate a random number just like we did, but instead of displaying a concatenated string, we will switch the results to a few < p > elements.

This will require some refactoring, so first let's change our buttonClickedmethod to only calculate this new number, and we will store it on a new property called randomNumber.

<script>    
  const app = new Vue({      
    el: '#app',      
    data: {        
        myLocalProperty: 'Im a local property value',        
        randomNumber: 0 // 1      
    },      
    methods: {        
        buttonClicked() {          
         this.randomNumber = Math.floor(Math.random() * 100); // 2        
    }      
  }   
  });  
 </script>

Let's resume:

  1. We've added a new local property randomNumber, and the default value will be 0.
  2. We deleted the old code, and instead of using the random value on the previous string we will just store it provisionally in our randomNumberprop.

We want to show/hide content depending on the result of our randomNumbercalculation, so let's have two new <p> elements. One will show only when randomNumber is greater or equal to 50. The other will show if it is less than 50.

<div id="app">    
 <p>My local property: {{ myLocalProperty }}</p>   
 <hr>    
 <button @click="buttonClicked">Click me</button>    
 <hr>    
 <!-- 1 -->    
 <p v-if="randomNumber >= 50">randomNumber is >= 50!</p>      
 <!-- 2 -->    
 <p v-else>Sorry, randomNumber is only <b>{{ randomNumber }}</b></p>  
</div>

We've added a <hr> for clary and separation, and then our two <p>elements.

Let's take a closer look to each one.

First, v-if="randomNumber >= 50". So, v-if is a Vue directive.

Don't get too caught up in the definition of the term, it only means that it is a "special" value that Vue knows how to read and interpret in HTML elements.

Theory aside, v-if tells Vue to only show this element if the condition we declare inside of it is true. In this case, "Vue: only show this <p> element IF and only IF randomNumber is greater than or equal that 50".

Second, whenever you have a v-if directive, you can have an else case.

But v-else only works on an element that directly follows the one that holds the v-if (or a third option v-else-if). As you'd expect from any if - else statement, the element with v-else will get rendered on any other case that is not true for the first. Either/or.

Go ahead and refresh the index.html and click a few times on the button. The < p > tags will be rendered reactively depending on the randomNumber value.

v-if and v-show

If you're curious to open your dev tools while clicking, you'll notice something important thing. v-if is not display: block/hidden css switch toggle, it actually renders or destroys elements whenever the value of our conditional changes. If you want to have a visibility toggle directive, go ahead and try switching that first v-if for v-show and see what happens!

You may realize that the v - else declarative block is no longer displayed. That's because v - show is a lone - ranger and works alone. So what's the advantage of using v - show?

There is a quality and performance cost that you might want to consider when using v - if because Vue has to go and re - render the DOM , but this is a more extensive task than applying / removing css display properties.

Moral of the story: If you only switch a small / medium part of the app a couple of times, such as a menu bar, v-if usually does the trick. But if you switch to tabbed screens, for example, or large parts of your page, v-show may be cheaper in terms of performance, because your markup is not rewritten at all times.

(P.S. before we continue, set back again the directive to v - if or you might get console errors due to the v - else it is unpaired.)

Development tools

If you wanted to find out which value is randomized into randomNumber for our > = 50 condition without having to render it inside the < p > tag with our trusty { { }, then Vue has a fantastic tool for the job.

Go back and install the Devtools Chrome Vue or Firefox Vue.

So since many of us can open the file directly on our browser using the the the the the the the the the file / / protocol, if you're not seeing the extension working for you in chrome. Follow these steps first:

"To make it work for pages opened via file:// protocol, you need to check "Allow access to file URLs" for this extension in Chrome's extension management panel."

Right click the Vue icon on the extensions toolbar, click on manage extensions and then toggle the allow access switch.

Once you've added them to your favorite browser go ahead and open them (Open your dev tools by "inspecting" or using the browser menu, then navigate to the "View" tab on the development panel) while you are on the index.js page and you might notice a lot of nice things to play with.

You'll immediately notice a toolbar with some icons on the top right, which we'll look at when we look at Vuex and you can for now safely ignore.

However, the crucial thing on this screen is the tree of components. The dev tools allow you to inspect each component you create for a page, its properties (data) and later when we examine how state management interacts with it.

Click on the <Root> component, you will see:

myLocalProperty:"I'm a local property value"
randomnumber=0

Notice our two local properties, myLocalProperty and randomNumber. Click on your <button> a few times and see how the developer tools responds by showing you the changes in the randomNumber value.

This may not seem super impressive right now, but this tool will be your # 1 source of information when we start building a real world application or even your actual work projects.

A positive thing with local storage, for example, is that you can manually modify the values to test various states of your application. Hover the property you want to modify and you will get an edit button and a + and - button to increase or decrease the value (in the case of numerical properties).

With the absolute basics we have already covered: setup, events, properties and conditional rendering, you now have the building blocks to develop some enjoyable and reactive applications. But again, this scratches the surface of Vue's power and from here it only becomes more fun and entertaining.

Soon with the 4th part of the article

If you haven't already done so:

read the first part of the article

read the second part of the article

 
by Janeth Kent Date: 25-02-2019 javascript vueJs tutorial guide hits : 3690  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

How to use the codePointAt method in JavaScript

The JavaScript codePointAt method has more or less the same function as the charCodeAt method, used to get the 16-bit Unicode representation of the character at a certain position in…

How to check if a value is a number in JavaScript

In this short tutorial we are going to look at the various methods that exist to find out if a value is a number in JavaScript.   1. Using the isNaN() function   One…

How to use the charCodeAt method in JavaScript

The charCodeAt method is accepted by strings in JavaScript, returning the 16-bit Unicode code of the character at the position we pass as a parameter to the method. The charCodeAt method…

How to use the charAt method in JavaScript

The charAt method is accepted by strings in JavaScript, returning the position of the character passed as a parameter within the string. If the string contains multiple occurrences of the character…

Strings in JavaScript: What they are and how to use them

In this tutorial we are going to explain what strings are and how they are used in JavaScript. The tutorial is intended for people who are learning to program in…

Dates in local format with Javascript

In the articles we have about dates in JavaScript we were missing one about how to create dates in local format with JavaScript. That is to say, being able to…

Formatting hours in Javascript

Continuing with the set of articles that talk about internationalisation elements, like the previous one where we talked about relative dates in JavaScript, we will see in this one how…

Request data with prompt in JavaScript

After having published several articles about how to manipulate arrays and dates, today I will publish a post that some of you will find too basic and others will find…

Relative dates in JavaScript

One of the interesting things about the internationalisation library represented in the Int object is the handling of relative dates in Javascript. This handling allows us to represent a date…

How to access webcam and grab an image using HTML5 and Javascript

We often use webcams to broadcast video in real time via our computer. This broadcast can be viewed, saved and even shared via the Internet. As a rule, we need…

The JavaScript forEach loop

We have already talked about how to handle some of loops  types in Javascript including for, for-in and for-off loops. In the case of today we are going to see how…

What are React Hooks and what problems they solve

Working with React, - and before the release of Hooks in version 16.8 -  there was always the possibility to create components in three different ways based on a number of…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration