Working with Methods in Vue.js
In previous videos, we have seen how we can output data with string interpolation. But what if we need to output data based on certain rules or logic? In that case, it might be handy to have a function in which we can embed JavaScript logic. Or perhaps we want to fetch data from a remote service or something like that. For this purpose, it’s time to introduce a new property to our Vue instance; the methods property. This property should contain an object where the key is the name of a function, and the value is the function itself.
Let’s see an example of this. Let’s use my name as an example again, but this time stored in two different properties; firstName and lastName.
new Vue({
el: '#app',
data: {
firstName: 'Bo',
lastName: 'Andersen'
}
});
To output my full name, I could of course concatenate these two data properties with string interpolation with a space in-between, or simply output them by using string interpolation twice. But that wouldn’t be any fun, would it? Instead, let’s add a method (i.e. function), which can do this for us.
As mentioned early, functions have to be added under the methods property. Don’t worry too much about the terminology here; the property is named methods because this is what we call functions that are in the context of an object, and that can operate upon the data that is contained within the object. In this case, the object is the Vue instance.
new Vue({
el: '#app',
data: {
firstName: 'Bo',
lastName: 'Andersen'
},
methods: {
}
});
The key within this object will be the name of the method. In this case, the name getFullName seems appropriate and descriptive. The value is going to be a function.
new Vue({
el: '#app',
data: {
firstName: 'Bo',
lastName: 'Andersen'
},
methods: {
getFullName: function() {
}
}
});
Methods can be used for various things as you will see in the upcoming videos, but for now I want the method to return a string value that can be output through string interpolation. So how can we access the data properties within this method? Vue.js proxies our data and methods to be available in the this context. So by writing this.firstName, we can access the firstName property within the data object. Note that this is required. With this, we can easily concatenate the first and last name and return the result.
new Vue({
el: '#app',
data: {
firstName: 'Bo',
lastName: 'Andersen'
},
methods: {
getFullName: function() {
return this.firstName + ' ' + this.lastName;
}
}
});
Again, note that Vue.js proxies the data and methods keys to be available within the this context, so when writing this.firstName for example, we are accessing the firstName property within the data object. If we wanted to, we could access other methods from within our getFullName method by using the same approach, just with parenthesis at the end to make it a method invocation.
Alright, so now that we have implemented our method, let’s use it from within our template. This is as easy as you would expect it to be; simply write the method name followed by parenthesis.
<div id="app">
<h1>{{ getFullName() }}</h1>
</div>
As it turns out, Vue.js proxies methods as well in addition to the data object’s properties. If I run the code, we should see my name being output on the page.
Let’s try a slightly different approach. What if we wanted to pass the first and last name to the method as arguments instead of having the method access the data properties directly? We can easily do so by adding parameters to the method as we would do in vanilla JavaScript.
I am going to use different names for the parameters so that they do not match the properties of the data object, just to prove that we are no longer relying on those within our method.
new Vue({
el: '#app',
data: {
firstName: 'Bo',
lastName: 'Andersen'
},
methods: {
getFullName: function(first, last) {
return first + ' ' + last;
}
}
});
Then, within the template, we simply have to pass in the values by using the appropriate property names from the data object.
<div id="app">
<h1>{{ getFullName(firstName, lastName) }}</h1>
</div>
Running the code should give us the same result as before, and indeed it does.
You are not bound to return strings from a method that is used within string interpolation, although you will most commonly do so. You can also return objects and arrays for example. Let’s see how we can refactor our method to return an object instead of a string.
I can just return an object directly with a name property as you would expect – nothing out of the ordinary here.
new Vue({
el: '#app',
data: {
firstName: 'Bo',
lastName: 'Andersen'
},
methods: {
getFullName: function(first, last) {
return {
name: first + ' ' + last
};
}
}
});
In the template, we still invoke the method as before. Running the code will print out the object, which is not exactly what we want. So after the method invocation, we can simply write a period followed by the name of the property we want to access – name in this case. Running the code once again will show the same result. This would also work with nested objects.
Before ending this article, I just want to give you a word of caution. If you try to make use of ES6 arrow functions within the methods object, you will not be able to access other methods or data properties. This is because arrow functions are bound to the parent context, and therefore the this keyword will not refer to the Vue instance as you would expect. Therefore, any data properties or methods you would try to access this way, would be undefined. The solution is simple: use ES5 syntax for functions within the methods object.
These were the basics of using methods within the Vue instance and how to invoke them from a template. In the upcoming articles, we will see how we can use methods to respond to events and more.
Here is what you will learn:
- How to build advanced Vue.js applications (including SPA)
- How Vue.js works under the hood
- Communicating with services through HTTP
- Managing state of large applications with Vuex
- ... and much more!
