Rule Proposal: `vue/no-implicit-props-access`
Please describe what the rule should do:
Props can be referenced in the template using propName or props.propName. Former is convenient; latter is more explicit, provides a clear delineation between local state and props and is consistent with how props are accessed in script. Former could also feel counter-intuitive if you're using Typescript (but that's subjective).
The rule, when enabled, should flag any occurrence of implicit prop access in the template.
What category should the rule belong to?
- [x] Enforces code style (layout)
- [ ] Warns about a potential error (problem)
- [ ] Suggests an alternate way of doing something (suggestion)
- [ ] Other (please specify:)
Provide 2-3 code examples that this rule should warn about:
<template>
<div>
<!-- bad -->
<div v-if="myProp">
myProp: true
</div>
<!-- bad -->
<div>
myProp: {{ myProp }}
</div>
<!-- good -->
<div v-if="props.myProp">
myProp: true
</div>
<!-- good -->
<div>
myProp: {{ props.myProp }}
</div>
</div>
</template>
<script lang="ts">
export interface Props {
myProp: boolean;
}
const props = defineProps<Props>();
</script>
Additional context
I tried to look for existing rules and proposals but couldn't find anything on this subject. If this is already possible, please let me know. Thank you.
Seems like a good rule to me. Note that it sounds similar to #938, maybe both rules can be combined into one?
It's been a while since I've used the Options API, but I believe it would require some special considerations in general.
IIRC, the ways to access the props in Options API are propName, $props.propName and props.propName (for functional components).
For functional components it's pretty straightforward, the logic can be incorporated in this rule based on what was proposed in #938.
For other components, going by the OP proposition, the rule should only allow $props.propName but I'm not sure if that's a good idea because:
- This would have to be implemented for prop accesses in
scripttoo for consistency. - Since $-prefixed variables are considered low level, maybe having them all over your codebase would not be ideal?
- While this would help with delineating props and local state, it doesn't do much in terms of reducing magic (where's
$propscoming from?).
I'd go even a step further and customize the option to enforce props. as prefix or disallow it. That way, people can choose if they want the overhead but have clear indication of a prop in the template or the simplicity instead.