Skip to content

Rule Proposal: Prevent accessing props directly in the template #2095

Closed
@nasvillanueva

Description

@nasvillanueva

Please describe what the rule should do:
When using <script setup>, local variables declared with the same name as the props takes precedence over the props. To avoid potential issues where a locally declared variable has different values or type than the props, I think it would be nice to have a rule to enforce accessing props from a variable.

For instance, enforce accessing props from const props = defineProps(...), so in the template it will be {{ props.propsValue }}.

What category should the rule belong to?

[ ] Enforces code style (layout)
[x] 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:

WARN

<script setup lang="ts">
defineProps<{
  msg: string;
}>()

const msg = "override props";
</script>

<template>
  <div>{{ msg }}</div> <!-- vague reference? are you referencing the one from props or local? -->
</template>

WARN

<script lang="ts">
import { defineComponent, computed } from "vue";

export default defineComponent({
  props: {
    msg: String
  },
  setup: (props) => {
    const msg = computed(() => `Message: ${props.msg}`);
    
    return {
      msg
    };
  }
})
</script>

<template>
    <div>{{ msg }}</div> <!-- vague reference? are you referencing the one from props or local? -->
</template>

OK

<script setup lang="ts">
const props = defineProps<{
  msg: string;
}>()

const msg = "override props";
</script>

<template>
  <div>From local: {{ msg }}</div>
  <div>From props: {{ props.msg }}</div>
</template>

Additional context

I understand that there are cases where a component's <script setup> is basically calling defineProps with no local variable declaration, so maybe we should be able to allow that? But I'm not sure if it's feasible.

<script setup lang="ts">
defineProps<{
  msg: string;
}>()
</script>

<template>
  <div>{{ msg }}</div> <!-- Maybe Okay? -->
</template>

(Possibly) Related Issues

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions