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 : 5585  
 
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 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…

What are javascript symbols and how can they help you?

Symbols are a new primitive value introduced by ES6. Their purpose is to provide us unique identifiers. In this article, we tell you how they work, in which way they…

Callbacks in JavaScript

Callback functions are the same old JavaScript functions. They have no special syntax, as they are simply functions that are passed as an argument to another function. The function that receives…

How to create PDF with JavaScript and jsPDF

Creating dynamic PDF files directly in the browser is possible thanks to the jsPDF JavaScript library. In the last part of this article we have prepared a practical tutorial where I…

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…

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