Vue3 Fundamentals ยท Components, Props & Events

Validating props

Validating props

A prop that arrives with the wrong type, or not at all, breaks the component quietly. Vue lets you describe each prop so it can warn you when a parent gets it wrong.

Instead of a list of names, pass defineProps an object. Each key is a prop name, and its value describes the prop:

<script setup>
defineProps({
  count: { type: Number, required: true, default: 3 },
});
</script>
  • type is the constructor the value should match, such as Number or String.
  • required marks a prop the parent must pass.
  • default supplies a value when the parent omits the prop.

Vue checks the type in development and warns when a required prop is missing. The default is what keeps an optional prop usable: a parent that passes nothing still gets a sensible value.

Declare a prop without a default and it is undefined when the parent omits it, so the template renders an empty gap. The Test mounts your component with no props and checks the value it falls back to.

Challenge

The component breaks when the parent passes no count. Give the prop a sensible default: export an App component from App.vue that declares count as a Number prop with a default of 3, then renders it as 3 items.

The Test mounts your component with no props and expects the paragraph to read 3 items. The starter declares the type but no default, so the value is empty and the Test fails. Add the default.

App.vue
<script setup>
defineProps({ count: Number });
</script>

<template>
  <p>{{ count }} items</p>
</template>

No test run yet

The Test is hidden. Run it to check the Challenge โ€” you only see the result, never the test source.