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

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

In the previous article, we discovered out how to add Vue to our index.html with a regular < script > tag and we were able to add our first reactive property to the page.

Today, we will learn how to change this property through the user input field.

Our code should be similar to the following:

<html>
    <head>
        <title>Vue 101</title>
    </head>

    <body>
        <h1>Hello!</h1>
        <div id="app">
          <p>My local property: {{ myLocalProperty }}</p>
        </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'
            }
          });
        </script>
    </body>
</html>

To better demonstrate Vue's reactivity and to learn how to react to user events, we will add a button to our app that changes the value of our myLocalProperty.

Now, we have to add new button to our < div id="app" >.

<div id="app">
  <p>My local property: {{ myLocalProperty }}</p>
  <hr>
  <button>Click me</button>
</div>

Now, how does the button react if it is clicked?

If you come from a jQuery background your instinct might be to try something like this: $('button').click(); however, there is a golden rule in Vue. NEVER directly manipulate the DOM (elements in the HTML of the page).

Without going into super complex details, Vue keeps a virtual "copy" of your HTML and automatically records where and how to update it when properties change.

If you make changes to the DOM directly with JavaScript, you risk losing these changes and unexpected behavior when Vue returns the content, as it is unaware of these changes.

Let's move on with our project and add this event handler to the button:

<button v-on:click="myLocalProperty = 'The button has been clicked'">
  Click me
</button>

A few things are going on here.

v-on:click="" In Vue we have these "directives" that we can add to our HTML content.

A directive simply put is an HTML parameter that Vue can understand.

In that case, we'll tell Vue: Vue (v-) that, if the user clicks the button must react like this: "myLocalProperty = 'The button has been clicked'", which is simply an inline declaration to change the value of our property.

If you go ahead and open your index.html file now in the browser and click the button, you will see the string that we interpolated earlier inside the {{ }} in our code will react to our button modifying the property.

In most cases you will probably not find events set to HTML with v-on:[eventname] as we have in this example, because Vue has a very useful shorthands for this type of thing. @[event name].

Let's change our < button > click even to to use this shorthand:

<button @click="myLocalProperty = 'The button has been clicked'">Click me</button>

Methods

In most cases, when a user event like the click of a button is fired, you will need to do a lot more than changing the value of a variable. So let's learn about methods.

To continue with our example, let's call a function that will do something really simple: by adding a random number to a string, it will change the value of myLocalProperty.

Delete our previous implementation of @click and replace it with this:

<button @click="buttonClicked">Click me</button>

Notice that we're not adding a () after "buttonClicked". We can omit these when we are not passing any arguments to our function. For example, @click="changeName('Sylvia')".

Now that we have our button ready to execute buttonClicked on clicks, we need to write this function.

Vue has a special place to write functions that our Vue instance can use. This place is inside the { } we passed to our new Vue({ } ) line before.

We will create a methods: {} property that will hold an object filled with our functions.

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

        this.myLocalProperty = newText; // 4
      }
    }
  });
</script>

Let's analyse that:

  1. First one, we declare the methods property inside our Vue instance. As I mentioned, you will put here all your instance methods/functions.
  2. We declare buttonClicked() Inside the methods object { }, which is the function we are trying to call on our @click listener.
  3. We join the value of the rounded down value Math.floor of the result of multiplying the random value of 0-1 by 100 to a string and store it in a constant.
  4. We assign the value of our new string to myLocalProperty. Now be very careful about this tiny detail. When we assign new values to the properties inside the instance's data property (the one inside data: {}) you MUST access it through this.[ prop-name ].

The keyword refers to the Vue instance in the context of a method. Vue performs some magic behind the scenes so that by doing this.property = value you can read / write your properties in the data.

Now that we've set up everything, reload the index.html file and click the button. Each time you click on the button, the value of our interpolated{{}} string containing < p > is updated, each time the buttonClicked function is executed. The magic of Vue's reactivity comes into play once again.

We're just scratching the surface of what we can do with Vue so far, but as we progress through these articles, these small building blocks will soon be at the heart of your next incredible app.

If you haven't already done so, read the first part of the article

Read the 3th part! ;-)

 
by Janeth Kent Date: 25-02-2019 javascript vueJs tutorial guide hits : 6477  
 
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…

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…

Template Literals in JavaScript

Template literals, also known as template literals, appeared in JavaScript in its ES6 version, providing a new method of declaring strings using inverted quotes, offering several new and improved possibilities. About…

How to use the endsWith method in JavaScript

In this short tutorial, we are going to see what the endsWith method, introduced in JavaScript ES6, is and how it is used with strings in JavaScript. The endsWith method is…

Clicky