0
0
Vueframework~30 mins

Typing ref and reactive in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Typing ref and reactive in Vue 3 Composition API
📖 Scenario: You are building a simple Vue 3 app that tracks a user's profile information. You want to store the user's age as a single number and the user's profile as an object with name and email. You will use Vue's ref and reactive to hold this data and add TypeScript types to keep your code safe and clear.
🎯 Goal: Create a Vue 3 component using the Composition API where you:Define a typed ref for the user's age as a number.Define a typed reactive object for the user's profile with name and email as strings.Display the age and profile data in the template.
📋 What You'll Learn
Use ref with a type annotation for a number variable called age initialized to 30.
Use reactive with a typed object called profile having name and email as strings.
Use <script setup lang="ts"> syntax for the component.
Display age, profile.name, and profile.email in the template.
💡 Why This Matters
🌍 Real World
Typing reactive data in Vue helps prevent bugs and improves code clarity in real-world web apps that manage user data.
💼 Career
Vue developers often use TypeScript with Composition API to build maintainable and scalable frontend applications.
Progress0 / 4 steps
1
Setup Vue component with typed ref
Create a Vue 3 component using <script setup lang="ts">. Import ref from 'vue'. Then create a typed ref variable called age with type number and initialize it to 30.
Vue
Hint

Use ref(30) to create a typed ref holding the number 30.

2
Add typed reactive object for profile
Import reactive from 'vue'. Create a typed reactive object called profile with properties name and email both typed as string. Initialize name to 'Alice' and email to 'alice@example.com'.
Vue
Hint

Use reactive<{ name: string; email: string }>({ name: 'Alice', email: 'alice@example.com' }) to create the typed reactive object.

3
Add template to display age and profile data
Add a <template> section below the script. Inside it, display the age value and the profile.name and profile.email values using mustache syntax {{ }}. Use semantic HTML tags: a <section> with a heading <h2> and paragraphs <p> for each piece of data.
Vue
Hint

Use <section> with aria-label for accessibility and display data inside <p> tags.

4
Add basic styling and accessibility improvements
Add a <style scoped> block below the template. Use CSS to set the section's max-width to 20rem, add padding of 1rem, and set a border with 1px solid #ccc. Also add a media query for screens narrower than 400px to reduce padding to 0.5rem. This improves readability and responsiveness.
Vue
Hint

Use scoped styles to keep CSS local and add a media query for small screens.