Using ES6 arrow functions in Vue.js

Published on February 10, 2017 by

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.

Featured

Learn Vue.js today!

Take an online course and become an Vue.js champion!

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!
Vue.js logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

Leave a Reply

Your e-mail address will not be published.