Enjoy!
🤔 What are props?
In Vue, props are custom attributes that you can register on a child component. When a parent component uses a child component, it can pass data to it via props.
<!-- ParentComponent.vue -->
<template>
<ChildComponent title="Hello World!" />
</template>
<!-- ChildComponent.vue -->
<template>
<h1>{{ title }}</h1>
</template>
<script setup>
defineProps(['title'])
</script>
In the example above, the parent passes a title prop to ChildComponent.
While Vue won't throw an error if a prop has the wrong type (unless you're using TypeScript), defining types and defaults helps catch bugs early.
Tips:
- Use prop types and defaults for clarity.
- Prefer
defineProps with TypeScript in <script setup> for better DX (developer experience).
- Use
withDefaults when default values are needed.
- Avoid mutating props inside child components; use
emits to notify parents of changes.
🟢 Defining Props in Vue
Vue 3 offers two primary ways to define props, depending on the script setup syntax you're using.
The <script setup> syntax is a Composition API feature introduced in Vue 3.2 that allows for a more concise and readable way to write components.
Basic prop definition:
<script setup>
const props = defineProps(['title', 'subtitle'])
</script>
With type annotations (using TypeScript or JSDoc):
<script setup lang="ts">
interface Props {
title: string
subtitle?: string
}
const props = defineProps<Props>()
</script>
With default values and validation:
Use withDefaults to define default values.
<script setup lang="ts">
interface Props {
title: string
count?: number
}
const props = withDefaults(defineProps<Props>(), {
count: 0,
})
</script>
Using the Options API
If you're still using the Options API, props are defined inside the props option in your component.
<script>
export default {
props: {
title: {
type: String,
required: true,
},
count: {
type: Number,
default: 0,
},
},
}
</script>
📖 Learn more
If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this link or by clicking the image below:
Vue School Link
It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects 😉
🧪 Advance skills
A certification boosts your skills, builds credibility, and opens doors to new opportunities. Whether you're advancing your career or switching paths, it's a smart step toward success.
Check out Certificates.dev by clicking this link or by clicking the image below:
Certificates.dev Link
Invest in yourself—get certified in Vue.js, JavaScript, Nuxt, Angular, React, and more!
✅ Summary
Defining props in Vue 3 is straightforward and flexible, supporting both classic Options API and the modern Composition API with <script setup>. By mastering props, you improve code reusability, maintainability, and clarity in your Vue applications.
Take care and see you next time!
And happy coding as always 🖥️