0
0
Vueframework~30 mins

Composable with reactive state in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Composable with reactive state
📖 Scenario: You are building a small Vue 3 app that tracks a counter. You want to organize your code by creating a composable function that holds the counter state and logic. This helps keep your code clean and reusable.
🎯 Goal: Create a composable function using Vue's ref to hold a reactive counter state. Then use this composable inside a component to display and update the counter.
📋 What You'll Learn
Use Vue 3 Composition API with ref for reactive state
Create a composable function named useCounter
Inside the composable, define a reactive variable count initialized to 0
Provide a function increment inside the composable to increase count
Use the composable inside a Vue component to display the current count and a button to increment it
💡 Why This Matters
🌍 Real World
Composables help organize and reuse reactive state and logic in Vue apps, making code cleaner and easier to maintain.
💼 Career
Understanding composables is essential for modern Vue development and is commonly used in professional frontend projects.
Progress0 / 4 steps
1
Create the reactive state in a composable
Create a composable function called useCounter that imports ref from 'vue' and defines a reactive variable count initialized to 0 inside it.
Vue
Need a hint?

Remember to import ref from 'vue' and define count inside the function.

2
Add an increment function to the composable
Inside the useCounter composable, add a function called increment that increases count.value by 1. Return increment along with count.
Vue
Need a hint?

Define increment as a function that adds 1 to count.value.

3
Use the composable inside a Vue component
Create a Vue component using <script setup>. Import useCounter and call it to get count and increment. Use these in the template to show the count and a button that calls increment when clicked.
Vue
Need a hint?

Use <script setup> syntax and bind the button click to increment.

4
Add accessibility and finalize the component
In the template, add an aria-label to the button with the text Increment counter for accessibility. Also, wrap the content in a <section> tag.
Vue
Need a hint?

Use semantic <section> and add aria-label to the button for screen readers.