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 : 3854  
 
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

What are React Hooks and what problems they solve

Working with React, - and before the release of Hooks in version 16.8 -  there was always the possibility to create components in three different ways based on a number of…

Flattening arrays in JavaScript

When we are handling arrays that are arrays or have multiple dimensions it can be very useful to know how to flatten arrays in JavaScript. That is to say, to…

How to populate an array with random numbers in JavaScript

Some of you might think that what we explained in the article on how to populate an array with numbers, apart from the didactic part, would not have much applicability…

How to populate an array with numbers in JavaScript

Populate an array with numbers in JavaScript The first step is to initialise the array. So today we are going to see a simple way to do it and see how…

Top Javascript Libraries and Frameworks Part 2

What are JavaScript frameworks?   JavaScript frameworks are application frameworks that allow developers to manipulate code to meet their particular needs. Web application development is like building a house. You have the option…

How to Send Email from an HTML Contact Form

In today’s article we will write about how to make a working form that upon hitting that submit button will be functional and send the email (to you as a…

Top JavaScript libraries and frameworks part 1

JavaScript libraries and frameworks make it easy to develop websites and applications with a wide variety of features and functionality, all with dynamic, flexible and engaging features. According to a 2020…

Looping through a matrix with JavaScript

We were already talking about how to multiply arrays in JavaScript and we realised that we had not explained something as simple as traversing an array with Javascript. So we…

How to multiply matrices in JavaScript

It may seem strange to want to know how to multiply matrices in JavaScript. But we will see some examples where it is useful to know how to perform this…

JavaScript Formatting Date Tips

Something that seems simple as the treatment of dates can become complex if we don't take into account how to treat them when presenting them to the user. That is…

How to make a multilingual website without redirect

Today, we're going to talk about how to implement a simple language selector on the basic static website, without the need of any backend or database calls or redirection to…

Starting with Bootstrap-Vue step by step

Today we will show you how to use BootstrapVue, describe the installation process and show basic functionality. The project’s based on the world's most popular CSS framework - Bootstrap, for building…

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