4 min read
•Question 7 of 37easyHow do Props work in Vue?
Passing data from parent to child components.
What You'll Learn
- Defining props
- Prop validation
- Props best practices
Defining Props
code.txtVUE
<!-- ChildComponent.vue -->
<script setup>
const props = defineProps({
title: String,
count: {
type: Number,
required: true
},
items: {
type: Array,
default: () => []
}
})
</script>
<template>
<h1>{{ title }}</h1>
<p>Count: {{ count }}</p>
</template>Using Props
code.txtVUE
<!-- ParentComponent.vue -->
<template>
<ChildComponent
title="Hello"
:count="5"
:items="['a', 'b']"
/>
</template>TypeScript Props
code.txtVUE
<script setup lang="ts">
interface Props {
title: string
count?: number
items?: string[]
}
const props = withDefaults(defineProps<Props>(), {
count: 0,
items: () => []
})
</script>Prop Validation
code.jsJavaScript
defineProps({
age: {
type: Number,
validator: (value) => value >= 0
}
})