Vue Props

Vue Props

Components are great, but they are completely isolated from one another.

What if the parent component has data that the child component needs to display?

To pass data downwards from a parent to a child, we use "Props" (short for properties).


Declaring Props in the Child

A child component cannot accept data unless it explicitly declares that it is expecting it.

In <script setup>, you use the defineProps() macro to declare the props you want to receive.

You pass an array of strings, where each string is the name of the expected prop.

Child Component (BlogPost.vue):

<template>
  <h4>{{ title }}</h4>
</template>

<script setup> // Declaring that we expect to receive a 'title' prop defineProps(['title']) </script>


Passing Props from the Parent

Once the child has declared its props, the parent can pass data into them.

You pass data by adding custom attributes to the child component's HTML tag.

The attribute name must perfectly match the prop name declared in the child.

Parent Component (App.vue):

<template>
  <h1>My Awesome Blog</h1>
  

<!-- Passing static string data into the props --> <BlogPost title="My Journey with Vue" /> <BlogPost title="Why Props are Awesome" /> </template>

<script setup> import BlogPost from './BlogPost.vue' </script>


Binding Dynamic Props

In the example above, we passed static hardcoded strings.

However, you usually want to pass dynamic data from the parent's reactive state.

To pass dynamic variables, you must use the v-bind directive (or the : shorthand).

Dynamic Prop Binding:

<template>
  <!-- Binding a dynamic variable using the colon shorthand -->
  <BlogPost :title="latestPostTitle" />
</template>

<script setup> import { ref } from 'vue' import BlogPost from './BlogPost.vue'

const latestPostTitle = ref('Dynamic Data Binding Explained') </script>


Exercise 1 of 2

?

What is the primary purpose of a "Prop" in Vue?

Exercise 2 of 2

?

Which macro function is used inside the child component's script tag to declare the incoming data?