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.


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.

<title>Vue 101</title>      
<div id="app">            
<p>My local property: {{ myLocalProperty }}</p>            
<button @click="buttonClicked">Click me</button>          
<script src=""></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;                

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.

  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        

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>   
 <button @click="buttonClicked">Click me</button>    
 <!-- 1 -->    
 <p v-if="randomNumber >= 50">randomNumber is >= 50!</p>      
 <!-- 2 -->    
 <p v-else>Sorry, randomNumber is only <b>{{ randomNumber }}</b></p>  

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"

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 : 5412  
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 make your own custom cursor for your website

When I started browsing different and original websites to learn from them, one of the first things that caught my attention was that some of them had their own cursors,…

Node.js and npm: introductory tutorial

In this tutorial we will see how to install and use both Node.js and the npm package manager. In addition, we will also create a small sample application. If you…

How to connect to MySQL with Node.js

Let's see how you can connect to a MySQL database using Node.js, the popular JavaScript runtime environment. Before we start, it is important to note that you must have Node.js installed…

JavaScript Programming Styles: Best Practices

When programming with JavaScript there are certain conventions that you should apply, especially when working in a team environment. In fact, it is common to have meetings to discuss standards…

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

How to get DOM elements with JavaScript

When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you…

How to reverse an array in JavaScript

In this tutorial we are going to see how you can change the order of the elements of an array so that they are inverted. You could use a loop…

How synchronize the scroll of two divs with JavaScript

In case you have two divs of different sizes you may sometimes want to scroll both at the same time but at different speeds depending on their size. For example,…

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…

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