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 : 3408  
 
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

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…

Flattening arrays in JavaScript

When we are handling arrays that are arrays or have multiple dimensions it can be very useful to know how to flatten arrays in JavaScript. That is to say, to…

How to populate an array with random numbers in JavaScript

Some of you might think that what we explained in the article on how to populate an array with numbers, apart from the didactic part, would not have much applicability…

How to populate an array with numbers in JavaScript

Populate an array with numbers in JavaScript The first step is to initialise the array. So today we are going to see a simple way to do it and see how…

Top Javascript Libraries and Frameworks Part 2

What are JavaScript frameworks?   JavaScript frameworks are application frameworks that allow developers to manipulate code to meet their particular needs. Web application development is like building a house. You have the option…

How to Send Email from an HTML Contact Form

In today’s article we will write about how to make a working form that upon hitting that submit button will be functional and send the email (to you as a…

Top JavaScript libraries and frameworks part 1

JavaScript libraries and frameworks make it easy to develop websites and applications with a wide variety of features and functionality, all with dynamic, flexible and engaging features. According to a 2020…

Looping through a matrix with JavaScript

We were already talking about how to multiply arrays in JavaScript and we realised that we had not explained something as simple as traversing an array with Javascript. So we…

How to multiply matrices in JavaScript

It may seem strange to want to know how to multiply matrices in JavaScript. But we will see some examples where it is useful to know how to perform this…

JavaScript Formatting Date Tips

Something that seems simple as the treatment of dates can become complex if we don't take into account how to treat them when presenting them to the user. That is…

How to make a multilingual website without redirect

Today, we're going to talk about how to implement a simple language selector on the basic static website, without the need of any backend or database calls or redirection to…

Starting with Bootstrap-Vue step by step

Today we will show you how to use BootstrapVue, describe the installation process and show basic functionality. The project’s based on the world's most popular CSS framework - Bootstrap, for building…

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