0
0
Vueframework~30 mins

Composable accepting parameters in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Composable Accepting Parameters in Vue 3
📖 Scenario: You are building a Vue 3 app that tracks a user's favorite color and allows updating it. You want to create a reusable composable function that accepts the initial color as a parameter and manages the color state.
🎯 Goal: Create a composable function called useFavoriteColor that accepts an initial color parameter and returns a reactive color state and a function to update it. Then use this composable in a Vue component to display and change the favorite color.
📋 What You'll Learn
Create a composable function useFavoriteColor that accepts a parameter initialColor.
Inside the composable, create a reactive variable color initialized with initialColor.
Create a function updateColor inside the composable to change the color value.
Return color and updateColor from the composable.
Use the composable inside a Vue component to show the current color and a button to change it.
💡 Why This Matters
🌍 Real World
Creating composable functions that accept parameters helps you write reusable and flexible code in Vue apps, making it easier to manage state and logic across components.
💼 Career
Understanding composables and parameter passing is essential for modern Vue development, improving code organization and maintainability in professional projects.
Progress0 / 4 steps
1
Create the composable function with a parameter
Create a composable function called useFavoriteColor that accepts a parameter named initialColor. Inside it, create a reactive variable called color initialized with initialColor. Use Vue's ref to make color reactive.
Vue
Need a hint?

Use ref(initialColor) to create a reactive variable inside the composable.

2
Add a function to update the color inside the composable
Inside the useFavoriteColor composable, add a function called updateColor that accepts a parameter newColor and sets color.value to newColor. Return updateColor along with color.
Vue
Need a hint?

Define updateColor as a function that changes color.value.

3
Create a Vue component that uses the composable
Create a Vue component using <script setup>. Import useFavoriteColor and call it with the initial color 'blue'. Destructure color and updateColor from the composable. Display the current color inside a <p> tag and add a button that calls updateColor('red') when clicked.
Vue
Need a hint?

Use @click on the button to call updateColor('red').

4
Add accessibility and finalize the component
Add an aria-label attribute to the button with the value 'Change favorite color to red' for accessibility. Also, add a role="region" and aria-live="polite" to the <p> tag to announce color changes to screen readers.
Vue
Need a hint?

Use aria-label on the button and aria-live on the paragraph for accessibility.