Composables
Composables are reusable functions that leverage Vue’s Composition API to encapsulate and reuse stateful logic. They are the composition API equivalent of mixins in the Options API, but with better type inference and more flexible composition patterns.What is a Composable?
A composable is a function that uses Vue’s reactive APIs (ref, reactive, computed, watch) to manage state and side effects. Composables typically:- Start with the prefix
use(e.g.,useMouse,useFetch) - Return reactive state and/or methods
- Can be composed together to build complex functionality
- Are reusable across multiple components
Basic Example
Here’s a simple composable that tracks mouse position:Reactive State with ref and reactive
Composables use Vue’s reactivity APIs to create reactive state:Using ref
ref creates a reactive reference to a value. It’s ideal for primitive values and single objects:
Using reactive
reactive creates a reactive proxy of an object, deeply converting all nested properties:
Computed Values
Usecomputed to create derived state that automatically updates:
Watchers
Composables can usewatch to react to state changes:
watch
Watch one or more reactive sources and execute a callback when they change:watchEffect
Automatically track reactive dependencies and re-run:Watch Options
Based onruntime-core/src/apiWatch.ts, watchers support several options:
- immediate: Execute callback immediately with current value
- deep: Deep watch nested properties (number or boolean)
- flush: Control timing -
'pre','post', or'sync' - once: Run the watcher only once
Async Composables
Composables can handle async operations:Composable Composition
Composables can use other composables:Best Practices
1. Return Reactive State
Always return reactive values from composables:2. Use Consistent Naming
Prefix composables withuse and use descriptive names:
3. Accept Refs as Arguments
Accept both refs and raw values for flexibility:4. Cleanup Side Effects
Always cleanup side effects inonUnmounted: