0
0
Vueframework~30 mins

Typing component props in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Typing component props
📖 Scenario: You are building a simple Vue 3 component that shows a user's profile card. You want to make sure the component receives the correct types of data as props.
🎯 Goal: Create a Vue 3 component using the Composition API with <script setup> that accepts typed props for name (string), age (number), and isMember (boolean). Display these props in the template.
📋 What You'll Learn
Create a Vue 3 component with <script setup> syntax
Define props with explicit types: name as string, age as number, isMember as boolean
Use the props in the template to show the user's name, age, and membership status
Use the Composition API style for props typing
💡 Why This Matters
🌍 Real World
Typing props helps catch errors early and makes components easier to use and maintain in real projects.
💼 Career
Understanding how to type props is essential for Vue developers to build reliable and scalable applications.
Progress0 / 4 steps
1
Setup the component and define props object
Create a Vue 3 component with <script setup> and define a props object with keys name, age, and isMember without types yet.
Vue
Hint

Start by creating a props object with keys name, age, and isMember. You don't need to add types yet.

2
Add types to the props using defineProps
Replace the props object with defineProps and specify types: name as String, age as Number, and isMember as Boolean.
Vue
Hint

Use defineProps to declare the props with their types.

3
Display the props in the template
In the <template>, display the user's name, age, and isMember status inside paragraphs.
Vue
Hint

Use mustache syntax {{ }} to show each prop inside a paragraph.

4
Add default values for props
Modify the defineProps call to add default values: name default to "Guest", age default to 0, and isMember default to false.
Vue
Hint

Use the object form for each prop to add a default value.