0
0
VueHow-ToBeginner · 3 min read

How to Define Props in Script Setup in Vue 3

In Vue 3's script setup, define props by using the defineProps function which accepts an object or type declaration. This lets you declare props simply and access them directly in the setup block without extra boilerplate.
📐

Syntax

Use the defineProps function inside the <script setup> block to declare props. You can pass an object describing prop types or use TypeScript interfaces for type safety.

The returned value is a reactive object containing the props passed to the component.

vue
<script setup>
const props = defineProps({
  title: String,
  count: Number
})
</script>
💻

Example

This example shows a Vue component that accepts title and count props and displays them.

vue
<template>
  <div>
    <h1>{{ title }}</h1>
    <p>Count: {{ count }}</p>
  </div>
</template>

<script setup>
const props = defineProps({
  title: String,
  count: Number
})
</script>
Output
<h1>Welcome</h1> <p>Count: 5</p>
⚠️

Common Pitfalls

  • Forgetting to use defineProps inside <script setup> causes errors.
  • Trying to mutate props directly will not work because props are readonly.
  • Not declaring prop types can lead to unexpected behavior or lack of type checking.
vue
<script setup>
// ❌ Wrong: mutating props directly
const props = defineProps({ count: Number })
props.count = 10 // Error: props are readonly

// ✅ Correct: use a local state to modify
import { ref } from 'vue'
const props = defineProps({ count: Number })
const localCount = ref(props.count)
localCount.value = 10
</script>
📊

Quick Reference

Tips for defining props in script setup:

  • Use defineProps to declare props.
  • Props are readonly; use local state to change values.
  • Type your props for better tooling and error checking.
  • Access props directly without this.

Key Takeaways

Use defineProps inside