0
0
VueConceptBeginner · 3 min read

What is defineProps in Vue: Simple Explanation and Example

defineProps is a Vue Composition API helper used in <script setup> to declare the props a component accepts. It lets you define and type-check props simply and clearly without extra boilerplate code.
⚙️

How It Works

Imagine you have a component that needs to receive some information from its parent, like a letter passed between friends. In Vue, these pieces of information are called props. defineProps is like writing down what kind of letters your component expects to get.

When you use defineProps inside a <script setup> block, Vue automatically understands what props your component can accept. This means you don't have to write extra code to declare props separately. It’s like telling Vue upfront, "Hey, I expect these specific pieces of information," so Vue can check and prepare them for you.

This makes your code cleaner and easier to read, especially for beginners, because you focus only on what your component needs without extra ceremony.

💻

Example

This example shows a simple Vue component that uses defineProps to accept a title prop and display it.

vue
<template>
  <h1>{{ title }}</h1>
</template>

<script setup>
const { title } = defineProps({
  title: String
})
</script>
Output
<h1>Hello Vue</h1>
🎯

When to Use

Use defineProps whenever you create a Vue component with <script setup> and want to receive data from a parent component. It is perfect for passing simple values like strings, numbers, or objects.

For example, if you build a button component that needs a label or a card component that shows a user’s name, defineProps helps you declare these inputs clearly. It also helps Vue check that the right type of data is passed, reducing bugs.

Key Points

  • defineProps is used only inside <script setup> in Vue 3.
  • It declares what props a component accepts in a simple way.
  • It supports type checking for better code safety.
  • It removes the need for the older props option in components.

Key Takeaways

defineProps declares component props simply inside <script setup>.
It helps Vue know what data your component expects from its parent.
Using defineProps makes your code cleaner and easier to read.
It supports type checking to catch errors early.
Use it whenever you want to pass data into a Vue component.