# Methods
Just like in Object Oriented Programming, methods are the actions a Vue instance can perform. All the things that a Vue instance can do.
# Syntax
Remember that configuration object we mentioned before? We declare methods in there, in a "reserved" key called... you guessed it! methods
.
So it would look something like this:
new Vue({
data: {
message: 'hello'
},
methods: {
doSomething() {
console.log(this.message); // logs: 'hello'
}
}
});
2
3
4
5
6
7
8
9
10
So long as doSomething
is a key in the methods
object, and it is an object method Vue doesn't really care about the syntax you use to declare it. Let me show you an alternative syntax:
new Vue({
data: {
message: 'hello'
},
methods: {
doSomething: function() {
console.log(this.message); // logs: 'hello'
}
}
});
2
3
4
5
6
7
8
9
10
Let me show you what won't work as expected though:
new Vue({
data: {
message: 'hello'
},
methods: {
/* THIS DOES NOT WORK AS EXPECTED */
doSomething: () => {
console.log(this.message); // logs: undefined
}
}
});
2
3
4
5
6
7
8
9
10
11
Vue binds this
to the instance for you, and it means that if you try to use an arrow function, you will lose the access to anything that lives in the instance itself. In an arrow function this
would be window
instead, and that is not what you want.
Don't worry too much about it; just remember to use normal functions (I prefer the use of the newer ES6 syntax as shown in the first snippet above).
# Example
Here is a quick example of methods. You can access instance properties (this.whatever
) and thus, call other methods.
See the Pen 02a. Methods by @ackzell on CodePen.