0
0
VueHow-ToBeginner · 3 min read

How to Pass Data from Parent to Child in Vue

In Vue, you pass data from a parent to a child component using props. The parent sets attributes on the child component tag, and the child declares props to receive those values.
📐

Syntax

To pass data from a parent to a child in Vue, the parent uses an attribute on the child component tag, and the child declares props to accept that data.

  • Parent: Use <ChildComponent :propName="value" /> to pass data.
  • Child: Declare props: ['propName'] to receive the data.
vue
<template>
  <ChildComponent :message="parentMessage" />
</template>

<script setup>
import ChildComponent from './ChildComponent.vue'
const parentMessage = 'Hello from parent'
</script>
💻

Example

This example shows a parent component passing a greeting message to a child component using props. The child displays the message.

vue
<!-- ParentComponent.vue -->
<template>
  <ChildComponent :greeting="greetingMessage" />
</template>

<script setup>
import ChildComponent from './ChildComponent.vue'
const greetingMessage = 'Hi there, child!'
</script>


<!-- ChildComponent.vue -->
<template>
  <p>{{ greeting }}</p>
</template>

<script setup>
const props = defineProps({
  greeting: String
})
</script>
Output
Hi there, child!
⚠️

Common Pitfalls

Common mistakes when passing data from parent to child in Vue include:

  • Not declaring the props in the child component, so the data is not received.
  • Passing data without using the : (v-bind) prefix, which passes the value as a string instead of a variable.
  • Mutating props inside the child component, which is against Vue's one-way data flow.
vue
<!-- Wrong: Passing prop as string literal -->
<ChildComponent greeting="greetingMessage" />

<!-- Right: Use v-bind to pass variable -->
<ChildComponent :greeting="greetingMessage" />

<!-- Wrong: Mutating prop inside child -->
<script setup>
const props = defineProps({ greeting: String })
props.greeting = 'Changed' // ❌ Do not do this
</script>

<!-- Right: Use local data copy if needed -->
<script setup>
import { ref } from 'vue'
const props = defineProps({ greeting: String })
const localGreeting = ref(props.greeting)
</script>
📊

Quick Reference

Summary tips for passing data from parent to child in Vue:

  • Use props in the child to declare expected data.
  • Use : (v-bind) in the parent to pass variables, not strings.
  • Props are read-only inside the child; do not modify them directly.
  • Use defineProps in <script setup> for clean syntax.

Key Takeaways

Use props to pass data from parent to child components in Vue.
Always bind variables with :propName syntax in the parent component.
Declare props in the child component using defineProps or props option.
Do not mutate props inside the child; treat them as read-only.
Use script setup syntax for simpler and cleaner Vue components.