Using ES6 arrow functions in Vue.js

This entry is part 6 of 32 in the series Vue.js: From Beginner to Professional

Before moving on, I just want to mention a thing or two about the ES6 arrow functions. While they are really useful in many cases, you also have to be a bit cautious with them. Let’s take the example from the previous lecture and see what happens if we change the getFullName method to an arrow function.

getFullName: () => {
	return this.firstName + ' ' + this.lastName;
}

Now we suddenly see undefined undefined being displayed on the page instead of my name. That’s because arrow functions are bound to the parent context, and therefore this will not be the Vue instance as you would expect. Let’s actually see this by logging this to the console.

getFullName: () => {
	console.log(this);
	return this.firstName + ' ' + this.lastName;
}

As we can see, this refers to the Window object, which is not really what we expected. That’s why there are no firstName or lastName properties available to us in that context. In comparison, let’s see what is logged when we use a normal function as before.

getFullName: function() {
	console.log(this);
	return this.firstName + ' ' + this.lastName;
}

Now we see the Vue instance being output as we would have expected in the first place.

So, the moral of the story is that you should not use arrow functions on Vue instance properties where Vue tries to bind this to the Vue instance itself. There are still times where you can use arrow functions with all their benefits, for instance if you assign a function to a variable within one of your Vue instance’s methods. Then you can access this within this arrow function, and it would point to the Vue instance as you would expect. Just be aware of where you use these arrow functions and if you experience some strange behavior with this not point to what you expect, then it might be related to arrow functions. That’s just something to be aware of.

Series Navigation<< Working with Methods in Vue.jsIntroduction to Directives >>

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *