Skeletor
Skeletor

Reputation: 3403

Does defineProps in script setup automatically create a local property of the defined prop?

When we pass a prop to a component and define that prop from child component with defineProps a property somehow is created and accessible from child components template.

parentComponent.vue

<template>
    <child-component v-model="product">
</template>

<script setup>
import childComponent from "./childComponent.vue"
</script>

childComponent.vue

<template>
    {{ product }}
</template>

<script setup>
const props = defineProps(['product'])
</script>

Here in childComponents template, the product can be accessed without needing to use props.product or toRef it. I know that script setup automatically injects the used props but I could not find any info (in docs) that the defineProps does some too. Is there any info about that.

Upvotes: 2

Views: 2763

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

According to this section :

The script is pre-processed and used as the component's setup() function, which means it will be executed for each instance of the component. Top-level bindings in <script setup> are automatically exposed to the template. For more details

Knowing that props are unwrapped directly inside the template and also the refs are used without .value.

If you want to reference some prop inside the script you should use props.product like in this example :

<script setup>
const props = defineProps(['product'])

const total=computed(()=>props.product.quantity*props.product.unity_price))

</script>

if the prop is only accessed by template you could get rid off const props just call the macro defineProps :

<template>
    {{ product }}
</template>

<script setup>
defineProps(['product'])
</script>

Upvotes: 7

Related Questions