0
0
Vueframework~30 mins

Creating a custom composable in Vue - Try It Yourself

Choose your learning style9 modes available
Creating a Custom Composable in Vue 3
📖 Scenario: You are building a simple Vue 3 app that tracks a counter. You want to reuse the counter logic in multiple components. To do this, you will create a custom composable function that manages the counter state and provides functions to change it.
🎯 Goal: Build a custom composable called useCounter that holds a counter value and provides increment and decrement functions. Then use this composable inside a Vue component to display and change the counter.
📋 What You'll Learn
Create a reactive counter variable using ref
Create a composable function named useCounter
Inside useCounter, define increment and decrement functions that update the counter
Return the counter and the two functions from useCounter
Use the useCounter composable inside a Vue component's setup function
Display the counter value and add buttons to call increment and decrement
💡 Why This Matters
🌍 Real World
Custom composables help you reuse logic like counters, form handling, or data fetching across many Vue components without repeating code.
💼 Career
Understanding composables is essential for modern Vue development and is a common skill required in frontend developer roles.
Progress0 / 4 steps
1
Setup the reactive counter variable
Import ref from vue and create a reactive variable called counter initialized to 0.
Vue
Need a hint?

Use ref(0) to create a reactive number starting at zero.

2
Create the useCounter composable function
Define a function called useCounter that returns an object with counter, increment, and decrement. Inside it, define increment and decrement functions that add or subtract 1 from counter.value.
Vue
Need a hint?

Return the reactive counter and the two functions inside an object.

3
Use the composable inside a Vue component
Create a Vue component with a setup function. Inside setup, call useCounter and get counter, increment, and decrement. Return these from setup.
Vue
Need a hint?

Destructure the returned object from useCounter() inside setup().

4
Add template to display and control the counter
Add a template section that shows the counter value inside a <span>. Add two buttons labeled + and - that call increment and decrement on click.
Vue
Need a hint?

Use @click on buttons to call the functions. Show counter inside {{ }}.