0
0
Vueframework~30 mins

Sharing composables across components in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Sharing composables across components
📖 Scenario: You are building a Vue 3 app with multiple components that need to share the same reactive counter logic.Instead of duplicating code, you will create a composable function to hold the counter state and increment logic.
🎯 Goal: Create a composable function useCounter that provides a reactive count and an increment function. Then use this composable in two separate components to share the counter state.
📋 What You'll Learn
Create a composable function named useCounter that returns a reactive count and an increment function.
Use Vue's ref to make count reactive.
Create two components named CounterOne and CounterTwo that both use useCounter.
Display the current count and a button to call increment in each component.
💡 Why This Matters
🌍 Real World
Composables let you write reusable logic once and use it in many components, saving time and reducing bugs.
💼 Career
Understanding composables is essential for Vue developers to build clean, maintainable, and scalable applications.
Progress0 / 4 steps
1
Create the composable function useCounter
Create a composable function named useCounter that uses Vue's ref to create a reactive variable called count initialized to 0. Also create a function named increment that increases count.value by 1. Return both count and increment from useCounter. Use import { ref } from 'vue' at the top.
Vue
Need a hint?

Use ref(0) to create a reactive count. Define increment to add 1 to count.value. Return both in an object.

2
Create the CounterOne component using useCounter
Create a Vue component named CounterOne using <script setup>. Import the useCounter composable. Call useCounter() and destructure count and increment. In the template, display the text Counter One: {{ count }} and a button with text Increment that calls increment on click.
Vue
Need a hint?

Use <script setup> syntax. Import useCounter and call it to get count and increment. Use a button with @click to call increment.

3
Create the CounterTwo component using useCounter
Create a Vue component named CounterTwo using <script setup>. Import the useCounter composable. Call useCounter() and destructure count and increment. In the template, display the text Counter Two: {{ count }} and a button with text Increment that calls increment on click.
Vue
Need a hint?

Repeat the same pattern as CounterOne but change the displayed text to Counter Two.

4
Use both components in a parent component
Create a parent Vue component named App using <script setup>. Import CounterOne and CounterTwo components. Register them locally by importing. In the template, include both <CounterOne /> and <CounterTwo /> tags to display both counters on the page.
Vue
Need a hint?

Import both components and include them in the template using their tags.