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

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

A Java approach: The Cycles - Introduction

Hello everyone and welcome back! Until now, we have been talking about variables and selection structures, going to consider some of the fundamental aspects of these two concepts. Theoretically, to…

A Java Approach: Selection Structures - Use Cases

Hello everyone and welcome back! Up to now we have been concerned to make as complete an overview as possible of the fundamental concepts we need to approach the use…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

A Java approach: boolean variables

The previous time, we talked extensively about Boolean variables, trying to outline the main operations that can be carried out at a practical level.  Of all the cases examined, we have…

A Java approach: condtional structures

Hello everyone and welcome back! The previous times we have introduced the concept of variable, trying to define some basic concepts about it.  However, some situations suggest that the concept of…

Hashmap: hashing, collisions and first functions

Today we are going to study some concepts closely related to hashmaps. The concepts we are going to see are hashing and collisions. Hashing The idea of hashing with chaining is to…

Hashmap: Overflow Lists

In this short series of articles we will go to see how it is possible to create the Hashmap data structure in C. In the implementation we're going to use the…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

A Java approach: variables

Hello everyone and welcome back! Today we will begin a journey that will lead us to study, and possibly review, what are the basics of programming. We will start by talking…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

The package managers npm and yarn: main differences

Npm and yarn are package managers that help to manage a project’s dependencies. A dependency is, as it sounds, something that a project depends on, a piece of code that…

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