Components and props

Beginner · 15 min

Splitting an app into child components, declaring props with defineProps, validation and defaults, Vue 3.5 props destructure, and one-way data flow.

Before thisref and reactiveList rendering with v-for

Also taught inReact

VueReference · 15 min

Components and props

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by VueReferenceReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A component is a reusable single-file component that a parent imports and uses as a tag. In `<script setup>`, importing it is enough to register it for that template.
  • Props are the component's declared inputs. `defineProps` lists them, either as runtime options (`{ title: String }`) or as a TypeScript type (`defineProps<{ title: string }>()`), and anything not declared is not a prop.
  • Data flows one way. The parent owns the value and passes it down; the child reads it, and Vue warns if the child tries to assign to a prop. To change it, the child asks the parent with an event.
  • Static attributes pass strings. To pass a number, boolean, array, object, or a variable, bind it with `:` so the value is evaluated as a JavaScript expression.
  • Since Vue 3.5, destructuring `defineProps()` stays reactive because the compiler rewrites `foo` into `props.foo`, and JavaScript default values work as prop defaults. Passing a destructured prop to `watch` or a composable still needs a getter, `() => foo`.
  • Props are optional unless marked `required`. A missing Boolean prop becomes `false`, and object or array defaults in the runtime syntax must come from a factory function.

Why split an app into components at all

A first Vue app usually lives in one App.vue. It works until the file holds a header, a list, a card layout repeated twenty times, and a form. Every change means scrolling past everything else, and the card markup gets copied each time it is needed.

Components fix this the same way functions fix a long script: give a piece of UI a name, put it in its own file, and reuse it. The general idea of building a UI from small composable parts is covered in component-based architecture. This lesson is about how Vue does it.

A child component is a single-file component like any other:

<!-- BlogCard.vue -->
<template>
  <article class="card">
    <h2>Untitled post</h2>
  </article>
</template>

In <script setup>, importing a component registers it for that template. There is no components: {} option to fill in:

<!-- App.vue -->
<script setup>
import BlogCard from './BlogCard.vue'
</script>

<template>
  <BlogCard />
  <BlogCard />
</template>

Each <BlogCard /> is a separate instance with its own state. The trouble is that both say “Untitled post”. A reusable component needs inputs.

Props are a component’s declared inputs

Think of a component as a function and props as its parameters. The child declares which inputs it accepts with the defineProps compiler macro:

<!-- BlogCard.vue -->
<script setup>
const props = defineProps({
  title: String,
  likes: Number,
})
</script>

<template>
  <article class="card">
    <h2>{{ title }}</h2>
    <p>{{ likes }} likes</p>
  </article>
</template>

Props are available directly in the template. In the script they live on the object defineProps returns, so you read props.title. defineProps is a macro, not an import: the compiler handles it, which is why it only works at the top level of <script setup>. The script setup lesson covers macros in general.

The parent passes values as attributes:

<BlogCard title="Why Vue" :likes="42" />

The colon matters. title="Why Vue" passes a static string. :likes="42" evaluates 42 as JavaScript and passes a number. Leave the colon off and the child receives the string "42". The same rule applies to booleans, arrays, objects, and any variable from the parent’s state, as covered in attribute binding.

Name props in camelCase in JavaScript (postTitle) and pass them in kebab-case in templates (post-title="..."). Vue converts between the two, so both refer to the same prop.

Rendering components from data

Props become useful when the data comes from somewhere. Combine a component with v-for and each item becomes a card:

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

const posts = ref([
  { id: 1, title: 'Why Vue', likes: 42 },
  { id: 2, title: 'Props in depth', likes: 7 },
])
</script>

<template>
  <BlogCard
    v-for="post in posts"
    :key="post.id"
    :title="post.title"
    :likes="post.likes"
  />
</template>

When an object’s keys line up with the prop names, v-bind="post" passes every key as a separate prop in one go.

Declaring props with types

With TypeScript, defineProps can take a type instead of a runtime object:

<script setup lang="ts">
const props = defineProps<{
  title: string
  likes?: number
}>()
</script>

The compiler turns the type into the equivalent runtime declaration. likes? makes it optional. Typing props properly, including imported interfaces and generics, is the job of the TypeScript with Vue lesson. Here it is enough to know both forms exist and do the same thing.

Validation, required, and defaults

The runtime object form takes more than a type. Each prop can have a full options object:

defineProps({
  title: { type: String, required: true },
  likes: { type: Number, default: 0 },
  tags: { type: Array, default: () => [] },
  status: {
    type: String,
    validator: (value) => ['draft', 'published'].includes(value),
  },
})

A few rules to know:

  • Props are optional by default. A missing optional prop is undefined, except Boolean props, which become false.
  • required: true produces a console warning in development when the parent leaves the prop out. It does not stop rendering.
  • Object and array defaults must be factory functions. A literal [] would be created once and shared by every instance.
  • Validators and type checks only run in development builds. They help catch mistakes, they don’t secure anything.

Reactive props destructure (Vue 3.5)

Destructuring is the natural way to pull values out of an object in JavaScript. Before Vue 3.5, destructuring defineProps() broke reactivity: you got a plain copy of each value that never updated. Since 3.5 the compiler handles it:

<script setup>
import { computed, watch } from 'vue'

const { title, likes = 0 } = defineProps(['title', 'likes'])

const label = computed(() => `${title} (${likes})`) // stays reactive
watch(() => likes, (n) => console.log('likes changed', n))
</script>

The compiler rewrites each use of likes in the same <script setup> block into props.likes, so computed and the template keep tracking it. The JavaScript default likes = 0 becomes the prop’s default.

One trap remains. watch(likes, ...) is rewritten to watch(props.likes, ...), which hands watch a plain number instead of something it can track. Wrap it in a getter, () => likes, the same way you would pass a destructured prop into a composable. Vue’s compiler warns about the plain form.

Props flow one way

The parent owns a prop’s value. When the parent’s state changes, the new value flows down and the child re-renders. The reverse never happens: the child must not assign to a prop.

const props = defineProps(['count'])
props.count++ // warning: props are readonly

The reason is predictability. If any child could rewrite a shared value, tracking down where a value changed means checking every component that receives it. With one-way flow the answer is always the owner.

When a child needs a prop as a starting point for its own state, copy it: const count = ref(props.count). When it needs a value derived from a prop, use computed. When it needs the parent’s value to actually change, it asks the parent by emitting an event, which is the subject of the next lesson.

React works the same way. Props are read-only there too, as covered in React’s components and props. The difference is that React passes callbacks as props, while Vue has a separate event channel for messages going up.

One caveat. Objects and arrays are passed by reference, so a child can mutate a nested property such as props.post.title = 'x' without a warning. Vue can’t cheaply stop it. Treat it as the same mistake.

What the video covers

VueReference’s tutorial starts from a starter project and does the core of this lesson step by step: registering a child component, declaring and passing a single prop, passing several props, then rendering a list of components from an array. The second half moves on to emitting events from the child, which is the next lesson’s topic. It was recorded before Vue 3.5, so reactive props destructure and the factory-default rules are covered above in prose. Syntax’s crash course is a good second view in current <script setup> with TypeScript, including a clear “don’t modify props” segment. Alexander Lichter’s video opens with a careful walkthrough of props destructure.

Check yourself

  1. 01Why does `<BlogPost likes="42" />` give the child a string, and how do you pass the number 42?

    A plain attribute in a template is a static string, just as in HTML. To pass any other type you bind it with `v-bind` or its `:` shorthand, `<BlogPost :likes="42" />`, which makes Vue evaluate the contents as a JavaScript expression and pass the resulting number.

  2. 02A child component receives `initialCount` as a prop and wants a counter it can increment. Why is `props.initialCount++` wrong, and what should it do instead?

    Props belong to the parent, so mutating one from the child breaks one-way data flow, and Vue warns about it in development. If the child only needs a starting value, it copies the prop into its own state, `const count = ref(props.initialCount)`. If the parent really owns the count, the child emits an event and lets the parent update it.

  3. 03In Vue 3.5, `const { size } = defineProps(['size'])` is reactive inside templates and computed values. Why does `watch(size, cb)` still not work?

    The compiler rewrites each access to `size` into `props.size`, so `watch(size, cb)` becomes `watch(props.size, cb)`, which hands `watch` the current value instead of a reactive source. Wrapping it in a getter, `watch(() => size, cb)`, gives `watch` something it can track. The compiler warns about the plain form.

  4. 04Why must an object or array default be written as `default: () => ({})` in the runtime props syntax?

    A plain object literal would be created once and shared by every instance of the component, so one instance mutating it would affect all the others. A factory function runs per instance and returns a fresh object each time. With reactive props destructure, a JavaScript default value in the destructuring pattern is evaluated per instance, so the issue goes away there.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark