eslint-plugin-vue
eslint-plugin-vue copied to clipboard
Rule Proposal: vue/no-arrow-for-properties
Please describe what the rule should do:
The rule would disallow the use of fat arrow functions data: () => {} inside components. Any component's options that are functions (e.g. data, methods, computed, head and other internal options) would have to use either data() {} or data: function() {}.
What category should the rule belong to?
- [X] Warns about a potential error
Code examples that this rule should warn about:
BAD
data: () => {
return {
value: this.getValue() // 'this' is not accessible
};
},
GOOD
data() {
return {
value: this.getValue() // Now 'this' is accessible
};
},
See this Codesandbox for an example of how using the arrow will result in not having access to this:
https://codesandbox.io/s/ly0mlmknx7
PS: the instance will be passed in as the first argument of the data function
data: (v) => {
return {
value: v.getValue()
};
},
PS: the instance will be passed in as the first argument of the function
Not the case with component methods though:
methods: {
getValue: (v) => {
v.foo; // error
this.foo; // error
},
},
@nathanchase that's correct. wouldn't make sense for methods :yum:
Is not no-invalid-this rule enough?
Is not no-invalid-this rule enough?
Perhaps to solve the 'this' issue specifically, but additionally having a rule that defines how the top-level instance options (data, components, methods, head, etc.) are written to keep consistency across an entire project would be helpful? I'm not aware of any other way via Prettier or otherwise to achieve that consistency.
I'm curious about which kind of a real use case that you would need this inside data().
I always thought that is something to avoid. Could you show me an example?
Fun fact: I found this issue searching for the opposite, I want to force arrow functions on data and asyncData (I'm using Nuxt) on my project
I'm curious about which kind of a real use case that you would need this inside data().
@SkyaTura You might want to create data based on passed props, for example. Or you might want to access some mixin or plugin.
But this rule should be more generic and apply to all component options (data, computed, methods, created, mounted, etc...). It makes even more sense in those places.
I want to force arrow functions on data and asyncData (I'm using Nuxt) on my project
Not sure why would you want to do that. The syntax is longer and 'messier' than function shorthand on object. And it will make it impossible to use this.
Using arrow function for asyncData wouldn't be a problem because that function is not bound to this (component doesn't exist yet) but IMO it's simpler and cleaner to use function shorthand.
Choosing between asyncData() { ... } and asyncData = () => { ... }, I'd choose former.