Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 87 ยท Components

Props

Learn how Vue 3 components receive data with props - declaring types, defaults, required and validator options, boolean casting, one-way data flow and the mutating-props pitfall.

A component that always shows the same thing is not very useful. Props (short for properties) are the inputs of a component: values that a parent passes in through attributes. A UserBadge receives a name, a ProductCard receives a title and a price. Props are how you turn a fixed piece of markup into a reusable one.

Props follow one strict rule that shapes everything else: data flows down, from parent to child, and the child must treat it as read-only. This lesson shows how to declare props with types and defaults, how booleans are treated specially, and what to do when a child needs a value that changes. If you are new to components, start with components basics.

flowchart TD
  P["Parent (owns the data)"] -- "props go down" --> C["Child (reads the data)"]
  C -. "events go up (next lesson)" .-> P

Props flow down; to ask the parent for a change, the child emits an event (see emits).

Declaring props

A component must declare the props it accepts. The simplest form is an array of names, and the more useful form is an object that describes each prop:

JavaScript
// array form: only names
props: ["title", "price"]

// object form: type, default, required, validator
props: {
  title: { type: String, required: true },
  price: { type: Number, default: 0 },
}

In an SFC with <script setup> you write the same thing with the compiler macro defineProps (it is not imported, and it is shown read-only here):

VUE
<script setup>
const props = defineProps({
  title: { type: String, required: true },
  price: { type: Number, default: 0 },
})
</script>

The object form gives you documentation, defaults and (in development builds) warnings when a parent passes something unexpected. The options of a prop are:

Option Meaning
type A constructor such as String, Number, Boolean, Array, Object, Function, Date, Symbol, or an array of them ([String, Number]).
required When true, the parent must pass it.
default Used when the parent passes nothing (or undefined). Objects and arrays need a factory function.
validator A function that receives the value and returns true when it is acceptable.

Attributes that are not declared as props are not props: they fall through to the root element (see fallthrough attributes).

Names: camelCase and kebab-case

Declare props in camelCase (inStock). In templates you can write either inStock or in-stock. The kebab-case form is the common convention because it looks like normal HTML, and it is the one that is required in in-DOM templates (see components basics).

Static and dynamic values

A plain attribute always passes a string. To pass anything else (a number, a boolean, an array, an object, a variable) bind it with v-bind or its : shorthand (binding attributes). price="9.5" passes the string "9.5", while :price="9.5" passes the number.

Types, defaults, required and boolean casting

Compare the three cards. The Mug passes in-stock with no value, which means true. The Poster passes nothing for inStock, so it is false; it also gets the default empty tags list and the default size m. The Lamp passes an explicit false and omits the price, so the default 0 is used. Each card shows how the declared type controls what the child receives.

Boolean casting

Props declared with the type Boolean get special treatment, mimicking HTML attributes like disabled:

  • Absent: false.
  • Present with no value (<Card in-stock />): true.
  • An empty string (in-stock=""): true as well.
  • Anything else must be bound: :in-stock="false".

If the type list contains both String and Boolean ([Boolean, String]), the order decides which wins for an empty value, so avoid that combination unless you need it.

Defaults: functions for objects

A default for an object or array must be returned from a factory function, so each instance gets its own copy:

JavaScript
tags: { type: Array, default: () => [] }
config: { type: Object, default: () => ({ theme: "light" }) }

A plain default: [] would be one array shared by every instance. Defaults are applied when the value is undefined, but not for null. null is a real value and passes through unchanged. A prop with required: true does not need a default, because the parent must always pass it.

Validators and what the checks do

A validator lets you restrict a prop to specific values, as size does above. The result is a development aid: when a prop has the wrong type, is missing but required, or fails its validator, Vue prints a warning in the browser console. It does not stop the component from rendering, and production builds skip these checks entirely. The examples in this track load the production build of Vue, so you will not see warnings in the preview. In a development build the console would read something like:

TEXT
[Vue warn]: Invalid prop: custom validator check failed for prop "size".

Treat validators as documentation for other developers. Do not rely on them for security, or for input from users, and handle unexpected values in the component where it matters. TypeScript gives stronger checking for props at build time (see TypeScript with Vue).

One-way data flow

All props form a one-way binding from parent to child. When the parent's value changes, the child receives the new value. The reverse never happens: a child cannot change the parent's data by assigning to a prop. This keeps the flow of data predictable, so when something on the screen is wrong you know to look upward to the component that owns it.

Props are exposed as a shallow readonly object. Reading props.title in setup is reactive, but assigning to it is not allowed (development builds enforce this with a warning). There are two common reasons a child wants to "change" a prop, and each has a standard answer.

1. The prop is only an initial value, and the child then owns the state. Copy it into a local ref:

JavaScript
const props = defineProps(["initialCount"])
const count = ref(props.initialCount)

Be aware of what this means: the copy is made once. If the parent later changes initialCount, the child's count does not follow. Name such props initial... or default... to make the contract obvious.

2. The prop needs transforming. Use a computed, which does follow the parent:

JavaScript
const label = computed(() => props.name.trim().toUpperCase())

The next TryIt shows both side by side. The parent has a number and a button that increases it.

Copying a prop versus computing from it

Press the parent button a few times. The "Computed from the prop" line follows (it doubles the new value), and the "parent says" text in the first child follows too, because that text reads the prop directly. But the local copy stays where it was: it started at 10 and only changes when you click it. That is the right behavior for an editable draft and a bug for something that should mirror the parent. Choosing between a copy and a computed is a decision about who owns the value.

The pitfall: changing props

Assigning to a prop is a bug. In a development build Vue warns that the target is readonly and the assignment fails. A production build does not check, so the child may appear to change while the parent never learns about it. The code is wrong either way:

JavaScript
props.count++   // a dev build refuses and warns: Set operation on key "count" failed: target is readonly.

There is a subtler trap. Readonly is shallow: only the prop itself is protected. If the parent passes an object or an array, the child can mutate the contents, and because it is the same object, the parent sees the change. Vue cannot warn you about that, and it makes data flow hard to follow, because the child silently edits something it does not own.

Assigning to a prop and mutating an object prop

Click the button. The child now shows count = 2, but the parent still says 1: because this page uses the production build, which does not enforce the readonly rule, the assignment only changed the child's local view, and the next time the parent passes a value it would be overwritten. (A development build would refuse the assignment and print the warning above.) The object edit is different: the name changes in the parent too. Either way the outcome is wrong, and that is exactly why the rule exists. If a child needs to request a change, it should tell the parent through an event and let the parent update its own data. That is the topic of events and emits, and for the common "input component" case, v-model on components packages the pattern. For a deeper look at this and related traps, see reactivity pitfalls.

Passing many props at once

To pass every property of an object as a separate prop, bind the object without an argument:

HTML
<ProductCard v-bind="product" />
<!-- same as: <ProductCard :title="product.title" :price="product.price" ... /> -->

It is a handy shortcut, but pass objects deliberately: a component with ten props is usually a hint that it does too much (see designing components).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A parent writes <Counter start="5" />. What does the child receive for start?

    A plain attribute always passes a string. Use :start="5" to pass the number.
  2. 2. How should a default array or object for a prop be written?

    Object and array defaults must come from a factory function, so each component instance gets its own copy instead of sharing one.
  3. 3. A component declares inStock: Boolean. Which usage passes true?

    A Boolean prop written as a bare attribute is cast to true, like HTML's disabled. Omitting it gives false.
  4. 4. A child needs a prop only as a starting value that it then edits. What is the recommended approach?

    Props are readonly. A local ref initialized from the prop gives the child its own editable state, with the understanding that later changes in the parent do not flow into it.
  5. 5. The parent passes a reactive object as a prop, and the child runs props.user.name = 'x'. What happens?

    Props are only shallowly readonly. The child holds a reference to the parent's object, so mutating its contents changes the parent's data. Avoid it; emit an event instead.

Summary

  • Props are the inputs of a component; declare them with the object form for types, defaults, required and validator.
  • Plain attributes pass strings; bind with : to pass numbers, booleans, arrays and objects.
  • Boolean props are cast: absent is false, a bare attribute is true.
  • Object and array defaults need factory functions; type and validator checks are warnings in development builds only.
  • Data flows one way. Copy a prop into a ref for a local draft, use computed for derived values, and never assign to a prop.
  • Props are only shallowly readonly, so mutating an object prop silently edits the parent's data; use events instead.

Next: Events and emits