Vue useCounter Composable Challenge
This challenge focuses on building a reusable and efficient useCounter composable function in Vue.js using TypeScript. A counter is a fundamental UI element, and creating a composable for it allows for easy integration into multiple components, promoting code reusability and maintainability.
Problem Description
You need to implement a useCounter composable function that manages a numeric counter value. This composable should provide functionality to increment, decrement, and reset the counter, as well as allow for an initial value to be set.
Key Requirements:
- State Management: The composable must manage a reactive counter value.
- Actions: Provide functions to:
increment(): Increase the counter by 1.decrement(): Decrease the counter by 1.reset(): Set the counter back to its initial value.
- Initial Value: The composable should accept an optional
initialValueargument, defaulting to 0. - Return Value: The composable should return an object containing the reactive
countand the action functions (increment,decrement,reset). - TypeScript: The entire implementation must be in TypeScript.
Expected Behavior:
When useCounter is called, it should return a reactive count ref and methods to manipulate it. Subsequent calls to these methods should update the count reactively.
Examples
Example 1: Basic Usage
// In a Vue component:
import { useCounter } from './useCounter'; // Assuming useCounter is in this file
const { count, increment, decrement } = useCounter();
// Initial state: count will be 0
// After increment(): count becomes 1
// After decrement(): count becomes 0
Example 2: With Initial Value
// In a Vue component:
import { useCounter } from './useCounter';
const { count, increment, reset } = useCounter(5);
// Initial state: count will be 5
// After increment(): count becomes 6
// After reset(): count becomes 5
Example 3: Resetting to Initial Value
// In a Vue component:
import { useCounter } from './useCounter';
const { count, increment, decrement, reset } = useCounter(10);
// Initial state: count will be 10
// After increment(): count becomes 11
// After increment(): count becomes 12
// After decrement(): count becomes 11
// After reset(): count becomes 10
Constraints
- The
initialValuemust be a number. - The
countmust always be a number. - The composable should be designed for use within the Vue 3 Composition API.
Notes
- Consider how to make the
countvalue reactive. - Think about the return type of the
useCounterfunction. - This composable is intended to be a pure function, meaning it doesn't rely on any external component-specific state.