DEV Community

Discussion on: What is "this"? Why you should avoid arrow functions on Vue methods

Collapse
 
iamschulz profile image
Daniel Schulz

I'd turn your statement around and say we should avoid this in Vue, but keep using arrow functions. Arrow functions are concise and eliminate the complexity of functions scopes. this can be hard to understand itself.
The composition API and it's setup method provide a way to define your reactive data, methods, etc. in one function. Watchers, refs and the likes are imported as functions as you go, eliminating any need for this.

Collapse
 
christiankozalla profile image
Christian Kozalla

Interesting. But I still code in Vue v2 and frequently use 'this' with regular functions. What's the point of giving up 'this' in favor of arrow functions, when it still works the way it is?

Collapse
 
iamschulz profile image
Daniel Schulz

If it works for you, then great :) I'm not telling you to refactor your entire codebase.

this is context aware and changes its meaning depending on its scope. That's inherently hard to read and understand.
Scope is also a problem that gets simpler with arrow functions, because they inherit their parent scope and don't create their own.
The point in giving up this is writing more readable code.

Collapse
 
js_bits_bill profile image
JS Bits Bill • Edited

Fair point. I find the composition API so radically different from the component based composition that it essentially becomes an architectural choice you'll have to make depending on your needs.