Data & Methods
Define data properties and methods on the Vue instance — use methods to perform actions and manipulate data from your templates.
Data & Methods
In the previous episode you learned about the data property. Now let us add methods — functions that can be called from your template to perform actions, change data, or return values.
Defining Methods
new Vue({
el: '#app',
data: {
name: 'Shaun',
job: 'Ninja',
age: 25
},
methods: {
greet: function() {
return 'Hello, I am ' + this.name + ' and I am a ' + this.job;
},
addAge: function(years) {
this.age += years;
}
}
});
Using this Inside Methods
Inside a method, this refers to the Vue instance. You access data properties with this.name, this.job, etc. You can also call other methods with this.methodName().
methods: {
greet: function() {
return 'Hello, ' + this.name; // this = Vue instance
},
changeName: function() {
this.name = 'Ken'; // Updates the data and the DOM
}
}
Calling Methods in Templates
<div id="app">
<h1>{{ greet() }}</h1>
<p>Age: {{ age }}</p>
<button v-on:click="addAge(1)">Add 1 year</button>
<button v-on:click="addAge(5)">Add 5 years</button>
</div>
Methods can be called in two ways: inside {{ }} to output a return value, or with v-on:click to respond to events (covered in depth next episode).
Methods vs Data
| Data | Methods |
|---|---|
| Stores values (strings, numbers, arrays, objects) | Contains functions that perform actions |
Accessed with {{ name }} | Called with {{ greet() }} (requires parentheses) |
| Reactive — DOM updates when values change | Can modify data, triggering DOM updates |
Defined in the data object | Defined in the methods object |
ES6 Shorthand
methods: {
// Long form
greet: function() { return 'Hello'; },
// ES6 shorthand (recommended)
greet() { return 'Hello'; }
}
Key Takeaways
- Methods are functions defined in the
methodsobject of the Vue instance - Inside methods,
thisrefers to the Vue instance — use it to access and modify data - Call methods in templates with
{{ methodName() }}or with event directives likev-on:click - When a method changes a data property, the DOM re-renders automatically