A Vue method is an object associated with the Vue instance. Functions are defined inside the methods object. Methods are useful when you need to perform some action with v-on directive on an element to handle events. Functions defined inside the methods object can be further called for performing actions.
Syntax:
methods : {
// We can add our functions here
}
Syntax for single file components:
export default {
methods: {
// We can add our functions here
}
}
In the following examples, we use Vue.js to show the working of methods.
Example 1:
HTML
<!DOCTYPE html><html>Â
<head>Â Â Â Â Â <script src=Â Â Â Â </script></head>Â
<body>Â
    <div style="text-align: center;" id = "home">Â
         <!-- Rendering data to DOM -->        <h1 style="color: seagreen;">{{title}}</h1>        <h2>Title : {{name}}</h2>        <h2>Topic : {{topic}}</h2>        <!-- Calling function in methods -->        <h2>{{show()}}</h2>Â
    </div>Â
</body><script type="text/javascript">Â
    // Creating Vue Instance    var vm = new Vue({Â
        // Assigning id of DOM in parameter        el: '#home',        // Assigning values of parameter        data: {            title : "Geeks for Geeks",            name : "Vue.js",            topic : "Instances"        },Â
        // Creating methods        methods : {Â
            // Creating function            show: function(){                return "Welcome to this tutorial on "                    + this.name + " - " + this.topic;            }        }    });</script>   </html> |
Â
Â
Output:
Â
Vue App
Â
Example 2:
Â
HTML
<!DOCTYPE html><html>Â
<head>Â Â Â Â <script src=Â Â Â Â </script></head>Â
<body>Â Â Â Â <div style="text-align: center;" id = "home">Â
        <!-- Rendering data to DOM -->        <h1 style="color: seagreen;">{{title}}</h1>        <h2>Title : {{name}}</h2>Â
        <!-- Calling function in methods -->        <button @click="show()">Click me</button>        <h2 id="view"></h2>    </div></body>Â
<script type="text/javascript">Â
    // Creating Vue Instance    var vm = new Vue({Â
        // Assigning id of DOM in parameter        el: '#home',Â
        // Assigning values of parameter        data: {            title : "Geeks for Geeks",            name : "Vue.js | Methods",        },Â
        // Creating methods        methods : {Â
            // Creating function            show: function(){                    // Setting text in element                    document.getElementById("view")                      .innerHTML = "Hi, This is Vue"Â
                    // Hiding text after 2 seconds                     setTimeout(() => {                        document.getElementById("view")                           .innerHTML = ""                    }, 2000);                }            }    });</script>Â
</html> |
Â
Â
Output:
Â
- Before clicking the button:Â
Â
Before click
- After clicking the button:Â
Â
After click
Â
