Vue.js Methods (original) (raw)
Last Updated : 10 Sep, 2021
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"
>
`` <
h1
style
=
"color: seagreen;"
>{{title}}</
h1
>
`` <
h2
>Title : {{name}}</
h2
>
`` <
h2
>Topic : {{topic}}</
h2
>
`` <
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"
>
`` <
h1
style
=
"color: seagreen;"
>{{title}}</
h1
>
`` <
h2
>Title : {{name}}</
h2
>
`` <
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