In Vue 3, defineProps is a macro used to define component props within the Composition API, which is used inside the <script setup> block. If you need to set default values for props, you should understand that defineProps is a compile-time sugar, so it does not natively support setting default values directly within function calls.
However, you can still set default values in several ways:
1. Using Destructuring and Default Values
The most straightforward way is to use ES6 destructuring assignment to provide default values when receiving props. This approach does not require modifying the defineProps call, but rather handles default values where props are used.
vue<script setup> const props = defineProps({ title: String, count: Number }); const { title = 'Default Title', count = 0 } = props; </script> <template> <h1>{{ title }}</h1> <p>Count: {{ count }}</p> </template>
In this example, if the parent component does not provide values for title or count, they will use 'Default Title' and 0 as default values.
2. Using withDefaults Macro
Vue 3.2 introduced a new macro withDefaults, specifically designed to set default values for defineProps within <script setup>. This is a clear and officially recommended way to handle default values.
vue<script setup> const props = withDefaults(defineProps<{ title?: string; count?: number; }>(), { title: 'Default Title', count: 0 }); </script> <template> <h1>{{ title }}</h1> <p>Count: {{ count }}</p> </template>
In this example, withDefaults is used to wrap the defineProps call and provide an object specifying default values for each prop. This not only makes the code clearer but also maintains type safety (if you are using TypeScript).
Summary
Although defineProps itself does not directly support default values, by using ES6 destructuring assignment or the withDefaults macro, we can conveniently set default values for component props. This ensures the flexibility and robustness of the component while maintaining code clarity and maintainability.