Vue.Js: a Quick Start Guide For Beginners. Part 3

by admin admin 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 admin admin Date: 25-02-2019 javascript vueJs tutorial guide hits : 1556  
 
 
 
 

Related Posts