0
0
Vueframework~30 mins

Prop types and validation in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Prop types and validation
📖 Scenario: You are building a simple Vue 3 component that displays user profile information. You want to ensure the component receives the correct types of data using props with validation.
🎯 Goal: Create a Vue 3 component named UserProfile that accepts props with specific types and validation rules. The component should accept a name prop as a required string, an age prop as an optional number, and a email prop as a required string with a custom validator to check it contains an '@' character.
📋 What You'll Learn
Use Vue 3 Composition API with <script setup>
Define props with types and validation
Make name a required string prop
Make age an optional number prop
Make email a required string prop with a custom validator checking for '@'
Render the props inside the template
💡 Why This Matters
🌍 Real World
Validating props ensures components receive the right data types and values, preventing bugs and improving reliability in real Vue applications.
💼 Career
Understanding prop types and validation is essential for frontend developers working with Vue to build robust, maintainable UI components.
Progress0 / 4 steps
1
Create the basic Vue component and define props object
Create a Vue 3 component using <script setup>. Define a props object with three props: name, age, and email. For now, just set name and email as strings and age as a number without validation.
Vue
Need a hint?

Use defineProps with an object specifying name, age, and email with their types.

2
Add required and optional prop configuration
Update the props object to make name and email required props, and keep age optional. Use the object syntax for each prop with type and required fields.
Vue
Need a hint?

Use the object syntax for each prop with type and required keys.

3
Add a custom validator for the email prop
Add a validator function to the email prop that returns true only if the email string contains the '@' character.
Vue
Need a hint?

The validator function should check if value.includes('@') returns true.

4
Render the props in the template
Inside the <template>, display the name, age, and email props inside separate paragraphs. Use mustache syntax like {{ name }} to show the values.
Vue
Need a hint?

Use mustache syntax inside paragraphs to show each prop value.