0
# VueUse Core
1
2
VueUse Core is a comprehensive collection of Vue 3 Composition API utilities providing 146+ reactive composable functions. These utilities cover common web development needs including state management, DOM manipulation, browser APIs, event handling, device sensors, network operations, and animation utilities. Built with TypeScript, it offers full type safety, SSR compatibility, and automatic cleanup.
3
4
## Package Information
5
6
- **Package Name**: @vueuse/core
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @vueuse/core`
10
11
## Core Imports
12
13
```typescript
14
import { useStorage, useMouse, useFetch, useVModel } from "@vueuse/core";
15
```
16
17
For individual imports (tree-shaking):
18
19
```typescript
20
import { useStorage } from "@vueuse/core/useStorage";
21
import { useMouse } from "@vueuse/core/useMouse";
22
```
23
24
CommonJS:
25
26
```javascript
27
const { useStorage, useMouse, useFetch, useVModel } = require("@vueuse/core");
28
```
29
30
## Basic Usage
31
32
```typescript
33
import { ref } from "vue";
34
import { useStorage, useMouse, useEventListener } from "@vueuse/core";
35
36
// Reactive localStorage with automatic serialization
37
const user = useStorage("user", { name: "", preferences: {} });
38
39
// Reactive mouse position
40
const { x, y } = useMouse();
41
42
// Event listener with automatic cleanup
43
useEventListener("click", () => {
44
console.log("Document clicked");
45
});
46
47
// Works with refs and reactive data
48
const count = ref(0);
49
const stored = useStorage("count", count);
50
```
51
52
## Architecture
53
54
VueUse Core is organized around several key design patterns:
55
56
- **Composable Functions**: Each utility follows Vue 3 composition API patterns with reactive returns
57
- **Automatic Cleanup**: All event listeners and resources are automatically cleaned up via `tryOnScopeDispose`
58
- **SSR Compatibility**: Server-side rendering safe with configurable SSR handlers
59
- **Configurable Options**: Consistent options patterns with sensible defaults across all functions
60
- **TypeScript Integration**: Full type safety with generic type preservation and inference
61
- **Reactive Returns**: Most functions return reactive refs that update automatically
62
63
## Capabilities
64
65
### State Management
66
67
Core reactive state utilities for managing component and application state with persistence and history tracking.
68
69
```typescript { .api }
70
function useStorage<T>(
71
key: string,
72
defaults: MaybeRefOrGetter<T>,
73
storage?: StorageLike,
74
options?: UseStorageOptions<T>
75
): RemovableRef<T>;
76
77
function useVModel<P extends object, K extends keyof P>(
78
props: P,
79
key?: K,
80
emit?: (name: string, ...args: any[]) => void,
81
options?: UseVModelOptions<P[K], true>
82
): WritableComputedRef<P[K]>;
83
```
84
85
[State Management](./state-management.md)
86
87
### DOM & Element Utilities
88
89
Reactive utilities for interacting with DOM elements, tracking element properties, and managing element state.
90
91
```typescript { .api }
92
function useElementSize(
93
target: MaybeComputedElementRef,
94
initialSize?: ElementSize,
95
options?: UseResizeObserverOptions
96
): {
97
width: Ref<number>;
98
height: Ref<number>;
99
stop: () => void;
100
};
101
102
function useActiveElement<T extends HTMLElement>(
103
options?: UseActiveElementOptions
104
): ShallowRef<T | null | undefined>;
105
```
106
107
[DOM & Element Utilities](./dom-elements.md)
108
109
### Mouse & Pointer Events
110
111
Comprehensive mouse and pointer event handling with multi-touch support and gesture detection.
112
113
```typescript { .api }
114
function useMouse(options?: UseMouseOptions): {
115
x: Ref<number>;
116
y: Ref<number>;
117
sourceType: Ref<UseMouseSourceType>;
118
};
119
120
function useDraggable(
121
target: MaybeComputedElementRef,
122
options?: UseDraggableOptions
123
): {
124
x: Ref<number>;
125
y: Ref<number>;
126
isDragging: Ref<boolean>;
127
position: ComputedRef<Position>;
128
style: ComputedRef<CSSProperties>;
129
};
130
```
131
132
[Mouse & Pointer Events](./mouse-pointer.md)
133
134
### Network & Communication
135
136
HTTP client utilities, WebSocket management, and browser communication APIs for data fetching and real-time communication.
137
138
```typescript { .api }
139
function useFetch<T>(
140
url: MaybeRefOrGetter<string>,
141
options?: RequestInit,
142
useFetchOptions?: UseFetchOptions
143
): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
144
145
function useWebSocket<Data = any>(
146
url: MaybeRefOrGetter<string | URL | undefined>,
147
options?: UseWebSocketOptions
148
): UseWebSocketReturn<Data>;
149
```
150
151
[Network & Communication](./network.md)
152
153
### Event Handling
154
155
Event listener management with automatic cleanup and specialized event utilities for common interaction patterns.
156
157
```typescript { .api }
158
function useEventListener<E extends keyof WindowEventMap>(
159
event: E,
160
listener: (this: Window, ev: WindowEventMap[E]) => any,
161
options?: ConfigurableWindow & AddEventListenerOptions
162
): Fn;
163
164
function onClickOutside(
165
target: MaybeElementRef,
166
handler: OnClickOutsideHandler,
167
options?: OnClickOutsideOptions
168
): Fn;
169
```
170
171
[Event Handling](./events.md)
172
173
### Browser APIs
174
175
Comprehensive browser API wrappers for clipboard, geolocation, permissions, notifications, theme management, and media device capabilities.
176
177
```typescript { .api }
178
function useClipboard(options?: UseClipboardOptions): UseClipboardReturn;
179
180
function useGeolocation(options?: UseGeolocationOptions): {
181
coords: Ref<GeolocationCoordinates>;
182
locatedAt: Ref<number | null>;
183
error: ShallowRef<GeolocationPositionError | null>;
184
resume: Fn;
185
pause: Fn;
186
};
187
188
function useColorMode<T extends string = BasicColorMode>(
189
options?: UseColorModeOptions<T>
190
): Ref<T | BasicColorMode>;
191
192
function useDark(options?: UseDarkOptions): WritableComputedRef<boolean>;
193
194
function useFullscreen(
195
target?: MaybeElementRef,
196
options?: UseFullscreenOptions
197
): UseFullscreenReturn;
198
```
199
200
[Browser APIs](./browser-apis.md)
201
202
### Device & Sensors
203
204
Device motion, orientation, battery status, and viewport utilities for responsive and context-aware applications.
205
206
```typescript { .api }
207
function useDeviceMotion(options?: UseDeviceMotionOptions): {
208
acceleration: Ref<DeviceMotionEventAcceleration | null>;
209
accelerationIncludingGravity: Ref<DeviceMotionEventAcceleration | null>;
210
rotationRate: Ref<DeviceMotionEventRotationRate | null>;
211
interval: Ref<number>;
212
};
213
214
function useBreakpoints<K extends string>(
215
breakpoints: Record<K, number | string>,
216
options?: UseBreakpointsOptions
217
): UseBreakpointsReturn<K>;
218
```
219
220
[Device & Sensors](./device-sensors.md)
221
222
### Animation & Effects
223
224
Animation utilities, scroll management, and visual effects for creating engaging user interfaces.
225
226
```typescript { .api }
227
function useScroll(
228
element: MaybeComputedElementRef,
229
options?: UseScrollOptions
230
): {
231
x: Ref<number>;
232
y: Ref<number>;
233
isScrolling: Ref<boolean>;
234
arrivedState: ScrollState;
235
directions: ScrollDirections;
236
measure(): void;
237
};
238
239
function useTransition(
240
source: Ref<number>,
241
options?: UseTransitionOptions
242
): Ref<number>;
243
```
244
245
[Animation & Effects](./animation-effects.md)
246
247
### Shared Utilities
248
249
Essential reactive programming utilities and helpers providing enhanced reactivity patterns, advanced computed properties, lifecycle helpers, and functional programming patterns.
250
251
```typescript { .api }
252
function computedEager<T>(fn: () => T): ComputedRef<T>;
253
254
function refDebounced<T>(
255
value: MaybeRefOrGetter<T>,
256
ms?: MaybeRefOrGetter<number>,
257
options?: DebounceFilterOptions
258
): Readonly<Ref<T>>;
259
260
function watchDebounced<T>(
261
source: WatchSource<T>,
262
cb: WatchCallback<T>,
263
options?: WatchDebouncedOptions
264
): WatchStopHandle;
265
266
function useToggle<T = boolean>(
267
initialValue?: MaybeRef<T>
268
): UseToggleReturn<T>;
269
```
270
271
[Shared Utilities](./shared-utilities.md)
272
273
### Template Composition
274
275
Advanced template composition utilities for creating reusable templates, template-based promises, and template reference helpers.
276
277
```typescript { .api }
278
function createReusableTemplate<
279
Bindings extends Record<string, any> = {},
280
Props extends Record<string, any> = {},
281
MapSlotNameToSlotProps extends Record<string, any> = {}
282
>(
283
options?: CreateReusableTemplateOptions<Props>
284
): ReusableTemplatePair<Bindings, MapSlotNameToSlotProps>;
285
286
function createTemplatePromise<Return = any, Args extends any[] = []>(
287
options?: TemplatePromiseOptions
288
): TemplatePromiseReturn<Return, Args>;
289
290
function templateRef<T extends Element | ComponentPublicInstance = Element>(
291
key?: string | number | symbol,
292
initialValue?: T | null
293
): Readonly<Ref<T | null>>;
294
```
295
296
[Template Composition](./template-composition.md)
297
298
### Utility Functions
299
300
Helper utilities for data manipulation, caching, type checking, and common programming patterns.
301
302
```typescript { .api }
303
function useMemoize<Args extends any[], Return>(
304
resolver: (...args: Args) => Return,
305
options?: UseMemoizeOptions<Args, Return>
306
): (...args: Args) => Return;
307
308
function useSupported(callback: () => unknown): ComputedRef<boolean>;
309
```
310
311
[Utility Functions](./utilities.md)
312
313
## Shared Types
314
315
```typescript { .api }
316
// Core configuration interfaces
317
interface ConfigurableWindow {
318
window?: Window;
319
}
320
321
interface ConfigurableDocument {
322
document?: Document;
323
}
324
325
// Common utility types
326
interface Position {
327
x: number;
328
y: number;
329
}
330
331
type PointerType = 'mouse' | 'touch' | 'pen';
332
333
type MaybeElementRef<T extends Element = Element> = MaybeRef<T | null | undefined>;
334
335
type MaybeComputedElementRef<T extends Element = Element> = MaybeRefOrGetter<T | null | undefined>;
336
337
// Storage interfaces
338
interface StorageLike {
339
getItem(key: string): string | null;
340
setItem(key: string, value: string): void;
341
removeItem(key: string): void;
342
}
343
344
interface UseStorageOptions<T> {
345
flush?: 'pre' | 'post' | 'sync';
346
deep?: boolean;
347
listenToStorageChanges?: boolean;
348
writeDefaults?: boolean;
349
mergeDefaults?: boolean | ((storageValue: T, defaults: T) => T);
350
serializer?: StorageSerializer<T>;
351
onError?: (error: Error) => void;
352
shallow?: boolean;
353
initOnMounted?: boolean;
354
}
355
```