DEV Community

Cover image for An introduction to methods in VueJs
mattiatoselli
mattiatoselli

Posted on

An introduction to methods in VueJs

In the last article we began our journey with Vue, going deeper, we'll introduce methods, which are going to be very useful for us. In this article we are only going to see a simple method.

In vue we can launch a method even without an event, like this for example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <!-- importing vue js dev library -->
    <!-- development version, includes helpful console warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <title>My vue Test</title>
</head>
<body>
    <div id="app">
        {{ sayHello() }}
    </div>
    <script type="text/javascript">
        var app = new Vue({ //instantiating the vue instance
          el: '#app', //we select where vue is going to work in the DOM
          data: {
            name: 'Mattia'//this are the data
          },
          methods: {
            sayHello: function() {
                return "Hello there, " +this.name;
            }
          }
        })
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

this is the resulting page:
image

Handling events

We can change datas or call functions with the directive "v-on:". Directives in Vue are like attributes that we can assign to different HTML elements.
This particular button for example, is going to change the name shown by our sayHello method:

<button v-on:click="name = 'Miyazaky'">My name is Miyazaky!</button>
Enter fullscreen mode Exit fullscreen mode

Of course, methods can have multiple lines of code, in this case, we can call a function using the name:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <!-- importing vue js dev library -->
    <!-- development version, includes helpful console warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <title>My vue Test</title>
</head>
<body>
    <div id="app">
        {{ sayHello() }}
        <br>
        <button v-on:click="changeName()">My name isn't {{ name }}!</button>
    </div>
    <script type="text/javascript">
        var app = new Vue({ //instantiating the vue instance
          el: '#app', //we select where vue is going to work in the DOM
          data: {
            name: 'Mattia'//this are the data
          },
          methods: {
            sayHello: function() {
                return "Hello there, " +this.name;
            },

            changeName: function() {
                if (this.name === "Mattia") {
                    this.name = "Miyazaki"; 
                } else {
                    this.name = "Mattia";
                }
            }
          }
        })
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)