0
0
Vueframework~5 mins

Prop types and validation in Vue

Choose your learning style9 modes available
Introduction

Props let you pass data to components. Validation helps catch mistakes early by checking the data type and rules.

When you want to send information from a parent component to a child component.
When you want to make sure the data passed to a component is the right type.
When you want to provide default values for props if none are given.
When you want to give clear errors or warnings if wrong data is passed.
When you want to document what kind of data a component expects.
Syntax
Vue
props: {
  propName: {
    type: [String, Number, Boolean, Array, Object, Function, Date, Symbol],
    required: true | false,
    default: defaultValue,
    validator: (value) => boolean
  }
}

The type checks the kind of data passed.

The validator is a function to add custom checks.

Examples
Simple prop expecting a string.
Vue
props: {
  title: String
}
Prop that must be a number and is required.
Vue
props: {
  count: {
    type: Number,
    required: true
  }
}
Prop with default value and custom validation to allow only certain strings.
Vue
props: {
  status: {
    type: String,
    default: 'active',
    validator: value => ['active', 'inactive'].includes(value)
  }
}
Sample Program

This component expects three props: title (string, required), count (number, required), and status (string with default and validation). It shows them in the template.

Vue
<template>
  <div>
    <h2>{{ title }}</h2>
    <p>Count: {{ count }}</p>
    <p>Status: {{ status }}</p>
  </div>
</template>

<script setup>
import { defineProps } from 'vue'

const props = defineProps({
  title: {
    type: String,
    required: true
  },
  count: {
    type: Number,
    required: true
  },
  status: {
    type: String,
    default: 'active',
    validator: value => ['active', 'inactive'].includes(value)
  }
})
</script>
OutputSuccess
Important Notes

If a required prop is missing or a prop fails validation, Vue will show a warning in the browser console.

Default values are used only if the prop is not provided.

Use validator for rules that type can't check, like allowed strings.

Summary

Props pass data from parent to child components.

Validation helps catch errors by checking type, required status, default values, and custom rules.

Vue shows warnings if props don't match the rules, helping you fix bugs early.