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

by Janeth Kent Date: 26-06-2023 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: 26-06-2023 javascript vueJs tutorial guide hits : 7747  
 
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 AND DEVELOPMENT.

 
 
 

Related Posts

How to upload files to the server using JavaScript

In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to…

How to combine multiple objects in JavaScript

In JavaScript you can merge multiple objects in a variety of ways. The most commonly used methods are the spread operator ... and the Object.assign() function.   How to copy objects with…

The Payment Request API: Revolutionizing Online Payments (Part 2)

In the first part of this series, we explored the fundamentals of the Payment Request API and how it simplifies the payment experience. Now, let's delve deeper into advanced features…

The Payment Request API: Revolutionizing Online Payments (Part 1)

The Payment Request API has emerged as the new standard for online payments, transforming the way transactions are conducted on the internet. In this two-part series, we will delve into…

Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3

HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images…

How do you stop JavaScript execution for a while: sleep()

A sleep()function is a function that allows you to stop the execution of code for a certain amount of time. Using a function similar to this can be interesting for…

Mastering array sorting in JavaScript: a guide to the sort() function

In this article, I will explain the usage and potential of the sort() function in JavaScript.   What does the sort() function do?   The sort() function allows you to sort the elements of…

Hidden Gmail codes to find a lost e-mail

If you have a lot of emails in Gmail, there are a few codes that will help you find what you need faster and more accurately than if you do…

How to download an email in PDF format in Gmail for Android

You will see how easy it is to save an email you have received or sent yourself from Gmail in PDF format, all with your Android smartphone. Here's how it's…

Infinite scrolling with native JavaScript using the Fetch API

I have long wanted to talk about how infinite scroll functionality can be implemented in a list of items that might be on any Web page. Infinite scroll is a technique…

Sorting elements with SortableJS and storing them in localStorage

SortableJS is a JavaScript extension that you will be able to use in your developments to offer your users the possibility to drag and drop elements in order to change…

What is a JWT token and how does it work?

JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…

Clicky