DEV Community

Jose Godinez
Jose Godinez

Posted on

ES6 arrow functions in Vue.js

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.

isRouteActive : (id) => {
if (this.$nuxt.$route.path.includes(id)) return true;
else return false;
}

As we can see, this refers to the Window object, which is not really what we expected.

isRouteActive(id) {
if (this.$nuxt.$route.path.includes(id)) return true;
else return false;
},

Now we see the Vue instance being output as we would have expected

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.

Top comments (0)