How to Create useCounter Composable in Vue 3
To create a
useCounter composable in Vue 3, define a function that uses ref to hold the count state and returns methods to modify it. This function can then be imported and used in any component to share counter logic easily.Syntax
The useCounter composable is a function that returns reactive state and functions to update it. It typically uses Vue's ref to create a reactive count variable and provides methods like increment and decrement.
This pattern helps you reuse logic across components without repeating code.
javascript
import { ref } from 'vue'; export function useCounter(initialValue = 0) { const count = ref(initialValue); function increment() { count.value++; } function decrement() { count.value--; } return { count, increment, decrement }; }
Example
This example shows how to create the useCounter composable and use it inside a Vue component to display and update a counter.
vue
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increase</button>
<button @click="decrement">Decrease</button>
</div>
</template>
<script setup>
import { useCounter } from './useCounter';
const { count, increment, decrement } = useCounter(5);
</script>Output
Count: 5
[Increase] [Decrease] buttons that update the count when clicked
Common Pitfalls
- Not using
reforreactivefor state, so updates donโt trigger reactivity. - Returning the state object directly without accessing
.valuein components. - Mutating state outside the composable functions, which can cause unpredictable behavior.
Always keep state inside the composable and expose functions to modify it.
javascript
/* Wrong way: count is a plain number, not reactive */ export function useCounterWrong() { let count = 0; function increment() { count++; } return { count, increment }; } /* Right way: count is reactive ref */ import { ref } from 'vue'; export function useCounterRight() { const count = ref(0); function increment() { count.value++; } return { count, increment }; }
Quick Reference
useCounter composable cheat sheet:
ref(initialValue): creates reactive count stateincrement(): function to increase countdecrement(): function to decrease count- Return state and functions from composable for use in components
Key Takeaways
Create a composable as a function returning reactive state and update methods.
Use Vue's ref to make count reactive and trigger UI updates.
Keep state inside the composable and expose functions to modify it.
Import and call the composable inside components to reuse logic easily.