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

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

Related Posts