0
# Common Utilities
1
2
General purpose utilities including counters, toggles, type conversions, lifecycle helpers, and basic data manipulation functions.
3
4
## Capabilities
5
6
### useCounter
7
8
Basic counter with increment, decrement, and reset functionality.
9
10
```typescript { .api }
11
/**
12
* Basic counter with increment/decrement controls
13
* @param initialValue - Initial counter value
14
* @param options - Counter options
15
* @returns Counter state and controls
16
*/
17
function useCounter(initialValue?: number, options?: UseCounterOptions): UseCounterReturn;
18
19
interface UseCounterOptions {
20
min?: number;
21
max?: number;
22
}
23
24
interface UseCounterReturn {
25
count: Ref<number>;
26
inc: (delta?: number) => number;
27
dec: (delta?: number) => number;
28
get: () => number;
29
set: (value: number) => number;
30
reset: (value?: number) => number;
31
}
32
```
33
34
**Usage Example:**
35
36
```typescript
37
import { useCounter } from "@vueuse/shared";
38
39
const { count, inc, dec, set, reset } = useCounter(0, {
40
min: 0,
41
max: 10
42
});
43
44
console.log(count.value); // 0
45
46
inc(); // count: 1
47
inc(5); // count: 6
48
dec(2); // count: 4
49
set(8); // count: 8
50
reset(); // count: 0 (back to initial)
51
reset(5); // count: 5 (reset to specific value)
52
53
// Respects min/max bounds
54
inc(10); // count: 10 (capped at max)
55
dec(15); // count: 0 (capped at min)
56
```
57
58
### useToggle
59
60
Boolean state with toggle functionality.
61
62
```typescript { .api }
63
/**
64
* Boolean state with toggle function
65
* @param initialValue - Initial boolean value
66
* @returns Toggle state and controls
67
*/
68
function useToggle(initialValue?: boolean): UseToggleReturn;
69
70
interface UseToggleReturn {
71
0: Ref<boolean>;
72
1: (value?: boolean) => boolean;
73
}
74
```
75
76
**Usage Example:**
77
78
```typescript
79
import { useToggle } from "@vueuse/shared";
80
81
const [isVisible, toggle] = useToggle(false);
82
83
console.log(isVisible.value); // false
84
85
toggle(); // true
86
toggle(); // false
87
toggle(true); // true (set specific value)
88
toggle(false); // false (set specific value)
89
90
// Destructuring alternative
91
const { 0: isOpen, 1: toggleOpen } = useToggle(true);
92
```
93
94
### get
95
96
Get the value of a ref, getter, or plain value.
97
98
```typescript { .api }
99
/**
100
* Get value of ref/getter/value
101
* @param obj - MaybeRefOrGetter to unwrap
102
* @returns Unwrapped value
103
*/
104
function get<T>(obj: MaybeRefOrGetter<T>): T;
105
```
106
107
**Usage Example:**
108
109
```typescript
110
import { get, ref, computed } from "@vueuse/shared";
111
112
const value = ref(42);
113
const getter = () => 'hello';
114
const plain = 'world';
115
116
console.log(get(value)); // 42
117
console.log(get(getter)); // 'hello'
118
console.log(get(plain)); // 'world'
119
120
// Useful for generic functions
121
function processValue<T>(input: MaybeRefOrGetter<T>): T {
122
const unwrapped = get(input);
123
// Process unwrapped value...
124
return unwrapped;
125
}
126
```
127
128
### set
129
130
Set value to a ref or call a setter function.
131
132
```typescript { .api }
133
/**
134
* Set value to ref/setter
135
* @param ref - Ref or setter function
136
* @param value - Value to set
137
*/
138
function set<T>(ref: Ref<T> | ((val: T) => void), value: T): void;
139
```
140
141
**Usage Example:**
142
143
```typescript
144
import { set, ref } from "@vueuse/shared";
145
146
const count = ref(0);
147
set(count, 42);
148
console.log(count.value); // 42
149
150
// Works with setter functions too
151
let localValue = 0;
152
const setter = (val: number) => { localValue = val; };
153
set(setter, 100);
154
console.log(localValue); // 100
155
```
156
157
### isDefined
158
159
Type guard to check if a value is defined (not null or undefined).
160
161
```typescript { .api }
162
/**
163
* Type guard to check if value is defined
164
* @param val - Value to check
165
* @returns Type-guarded boolean
166
*/
167
function isDefined<T>(val: T): val is NonNullable<T>;
168
```
169
170
**Usage Example:**
171
172
```typescript
173
import { isDefined } from "@vueuse/shared";
174
175
const maybeString: string | null | undefined = getValue();
176
177
if (isDefined(maybeString)) {
178
// TypeScript knows maybeString is string here
179
console.log(maybeString.length); // No type error
180
console.log(maybeString.toUpperCase()); // No type error
181
}
182
183
// Filter arrays
184
const values = [1, null, 2, undefined, 3];
185
const definedValues = values.filter(isDefined); // number[]
186
```
187
188
### makeDestructurable
189
190
Make an object both destructurable as object and array.
191
192
```typescript { .api }
193
/**
194
* Make object both destructurable as object and array
195
* @param obj - Object to make destructurable
196
* @param arr - Array representation
197
* @returns Object that can be destructured both ways
198
*/
199
function makeDestructurable<T extends Record<string, any>, A extends readonly any[]>(
200
obj: T,
201
arr: A
202
): T & A;
203
```
204
205
**Usage Example:**
206
207
```typescript
208
import { makeDestructurable } from "@vueuse/shared";
209
210
function usePosition() {
211
const x = ref(0);
212
const y = ref(0);
213
214
return makeDestructurable(
215
{ x, y }, // Object form
216
[x, y] // Array form
217
);
218
}
219
220
const position = usePosition();
221
222
// Object destructuring
223
const { x, y } = position;
224
225
// Array destructuring
226
const [posX, posY] = position;
227
228
// Both x and posX refer to the same ref
229
```
230
231
### until
232
233
Promised one-time watch for changes.
234
235
```typescript { .api }
236
/**
237
* Promised one-time watch for changes
238
* @param r - Source to watch
239
* @returns Until chain for conditions
240
*/
241
function until<T>(r: MaybeRefOrGetter<T>): UntilToMatch<T, false>;
242
243
interface UntilToMatch<T, Not extends boolean> {
244
/** Wait for value to be truthy */
245
toBeTruthy(): Promise<T>;
246
/** Wait for value to be falsy */
247
toBeFalsy(): Promise<T>;
248
/** Wait for specific value */
249
toBe<P = T>(value: MaybeRefOrGetter<P>): Promise<T>;
250
/** Wait for value to equal comparison */
251
toBeEqual<P = T>(value: MaybeRefOrGetter<P>): Promise<T>;
252
/** Wait for custom condition */
253
toMatch(condition: (v: T) => boolean): Promise<T>;
254
/** Wait for array to contain value */
255
toContains(value: any): Promise<T>;
256
/** Negate the condition */
257
not: UntilToMatch<T, true>;
258
/** Change to array matching */
259
array: UntilArrayToMatch<T>;
260
}
261
```
262
263
**Usage Example:**
264
265
```typescript
266
import { until, ref } from "@vueuse/shared";
267
268
const count = ref(0);
269
270
// Wait for truthy value
271
await until(count).toBeTruthy();
272
console.log('Count is now truthy:', count.value);
273
274
// Wait for specific value
275
await until(count).toBe(5);
276
console.log('Count is now 5');
277
278
// Wait for custom condition
279
await until(count).toMatch(n => n > 10);
280
console.log('Count is greater than 10:', count.value);
281
282
// Negated conditions
283
await until(count).not.toBe(0);
284
console.log('Count is no longer 0');
285
286
// With arrays
287
const items = ref<string[]>([]);
288
await until(items).toContains('target');
289
console.log('Items now contains "target"');
290
```
291
292
### Type Conversion Utilities
293
294
Reactive utilities for type conversions.
295
296
```typescript { .api }
297
/**
298
* Reactive number conversion
299
* @param value - Value to convert to number
300
* @param options - Conversion options
301
* @returns Computed ref with number value
302
*/
303
function useToNumber(
304
value: MaybeRefOrGetter<number | string>,
305
options?: UseToNumberOptions
306
): ComputedRef<number>;
307
308
interface UseToNumberOptions {
309
method?: 'parseFloat' | 'parseInt';
310
radix?: number;
311
nanToZero?: boolean;
312
}
313
314
/**
315
* Reactive string conversion
316
* @param value - Value to convert to string
317
* @returns Computed ref with string value
318
*/
319
function useToString(value: MaybeRefOrGetter<unknown>): ComputedRef<string>;
320
```
321
322
**Usage Examples:**
323
324
```typescript
325
import { useToNumber, useToString, ref } from "@vueuse/shared";
326
327
// Number conversion
328
const input = ref('42.5');
329
const asNumber = useToNumber(input, {
330
method: 'parseFloat',
331
nanToZero: true
332
});
333
334
console.log(asNumber.value); // 42.5
335
336
input.value = 'invalid';
337
console.log(asNumber.value); // 0 (because nanToZero: true)
338
339
// String conversion
340
const count = ref(42);
341
const asString = useToString(count);
342
343
console.log(asString.value); // '42'
344
345
count.value = 100;
346
console.log(asString.value); // '100'
347
```
348
349
### Date Formatting
350
351
Reactive date formatting utility.
352
353
```typescript { .api }
354
/**
355
* Reactive date formatting
356
* @param date - Date to format
357
* @param formatStr - Format string
358
* @param options - Formatting options
359
* @returns Computed ref with formatted date string
360
*/
361
function useDateFormat(
362
date: MaybeRefOrGetter<Date>,
363
formatStr?: MaybeRefOrGetter<string>,
364
options?: UseDateFormatOptions
365
): ComputedRef<string>;
366
367
interface UseDateFormatOptions {
368
locales?: MaybeRefOrGetter<string | string[]>;
369
}
370
```
371
372
### Lifecycle Utilities
373
374
Safe versions of Vue lifecycle hooks that work outside component context.
375
376
```typescript { .api }
377
/**
378
* Safe version of onBeforeMount
379
* @param fn - Function to execute
380
* @param sync - Execute synchronously if not in component
381
* @returns Whether hook was registered
382
*/
383
function tryOnBeforeMount(fn: Fn, sync?: boolean): boolean;
384
385
/**
386
* Safe version of onMounted
387
* @param fn - Function to execute
388
* @param sync - Execute synchronously if not in component
389
* @returns Whether hook was registered
390
*/
391
function tryOnMounted(fn: Fn, sync?: boolean): boolean;
392
393
/**
394
* Safe version of onBeforeUnmount
395
* @param fn - Function to execute
396
* @returns Whether hook was registered
397
*/
398
function tryOnBeforeUnmount(fn: Fn): boolean;
399
400
/**
401
* Safe version of onUnmounted
402
* @param fn - Function to execute
403
* @returns Whether hook was registered
404
*/
405
function tryOnUnmounted(fn: Fn): boolean;
406
407
/**
408
* Safe version of onScopeDispose
409
* @param fn - Function to execute
410
* @returns Whether hook was registered
411
*/
412
function tryOnScopeDispose(fn: Fn): boolean;
413
```
414
415
### Local Injection Utilities
416
417
Local fallback versions of provide/inject.
418
419
```typescript { .api }
420
/**
421
* Inject with local fallback
422
* @param key - Injection key
423
* @param defaultValue - Default value if not provided
424
* @returns Injected or default value
425
*/
426
function injectLocal<T>(key: InjectionKey<T> | string, defaultValue?: T): T;
427
428
/**
429
* Provide for local injection
430
* @param key - Injection key
431
* @param value - Value to provide
432
*/
433
function provideLocal<T>(key: InjectionKey<T> | string, value: T): void;
434
```