Methods in VueJS
In this tutorial, we will go over how you can define new methods in VueJS and also invoke them on user events.
Problem: You want to encapsulate the logic inside VueJS methods and also bind the methods to event actions.
Solution: As with other features, VueJS provides the simplest approach to defining methods inside the VueJS Instance and also binds them to a user event.
Look at the below screenshot for the application we are building.
Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.
We are building a simple greet application in VueJS, which on pressing the button prints out the appropriate greeting message.
var app = new Vue({
el: '#app',
data: {
greeting: '',
},
methods: {
greet: function(greeting){
this.greeting = greeting + ", How Are You?";
}
}
});
Notice the new object inside our Vue Instance named methods
. We can define as methods inside this object which defines the behaviour of our Vue Instance.
In this case, we have defined a single method named greet
, that accepts a single parameter named greeting
, and inside the method we have changed the data property greeting
using this
keyword.
Here is the HTML code which has three buttons and the greeting message displayed at the bottom.
<div id="app">
<h2>Greet</h2>
<button v-on:click="greet('Hello')">Say Hello</button>
<button v-on:click="greet('Hi')">Say Hi</button>
<button v-on:click="greet('Namaste')">Say Namaste</button>
<br/><br/>
{{greeting}}
</div>
We have invoked the greet method along with the appropriate parameters by using v-on
directive.
Demo
Greet
{{greeting}}
Practice Excercises
- Loop through an Array of names, accept user input from textbox to add new name to the list. (CodePen Solution Link