1

Here is the my fork from github example fiddle of vue.js offcial site: vue.js github example fiddle

I console.log(this) in fetchData function expression, and it outputs vue component instance: this output

But when I use arrow function with fetchData (fiddle of arrow function this), it console.log(this) is window

I had learned arrow function concept, but I still confuse this. Why the second fiddle this bind to the global window object, and the first fiddle this bind to vue component instance?

What condition can't I use arrow function this?

junlin
  • 1,835
  • 2
  • 25
  • 38

1 Answers1

2

You should never use an arrow function to define a method with Vue, because with arrow functions, this is defined lexically.

An arrow function does not create its own this, the this value of the enclosing execution context is used.

That means that, with Vue methods, this will point to the global object, or the window.

When a Vue is instantiated, Vue binds the methods defined in methods to the Vue object. An arrow function cannot be bound. It's this will always be the what it was originally.

That being the case, you should always use a normal function to write a Vue method.

This also applies to the data function, computed values, and lifecycle hooks. The only time you will generally use an arrow function is when you are defining a function inside one of your methods or computed values, as you might when defining a callback for an ajax call.

See VueJS: why is “this” undefined?.

Note: there is one exception to never using an arrow function to define a Vue method and that would be if you never referenced this at all in the method. Those cases are exceedingly rare. You almost always end up needing to reference other parts of the Vue inside a method using this. That being the case, it should quickly become a habit to simply never define a Vue method with an arrow function.

Bert
  • 80,741
  • 17
  • 199
  • 164
  • So many fall into this trap thinking anything ES6 is better. The same is true in jQuery event handlers and in React's `createClass`, when using arrow functions, know the implications! – Andrew Li Jul 05 '17 at 01:35
  • @AndrewLi Agreed. It's one of the most common mistakes I see. – Bert Jul 05 '17 at 01:38
  • @AndrewLi is this really the solution? My eslint goes beserk. In jQuery or React you would use bind function. From MDN web docs: The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. – sampoh Oct 24 '17 at 06:15