0
# Utilities and Composables
1
2
Utility functions and Vue 3 composables for common functionality including DOM manipulation, touch handling, and state management.
3
4
## Capabilities
5
6
### Composables
7
8
Vue 3 composables providing reusable logic for common mobile development patterns.
9
10
```typescript { .api }
11
import {
12
useRect,
13
useScrollParent,
14
useEventListener,
15
useToggle,
16
useCountDown,
17
useClickAway,
18
usePageVisibility,
19
useWindowSize,
20
useCustomFieldValue
21
} from 'vant';
22
23
// DOM measurement composable
24
function useRect(elementOrSelector: Element | Window | string | Ref<Element | undefined>): {
25
width: number;
26
height: number;
27
top: number;
28
left: number;
29
right: number;
30
bottom: number;
31
};
32
33
// Scroll parent detection
34
function useScrollParent(element: Ref<Element | undefined>): Ref<Element | Window>;
35
36
// Event listener management
37
function useEventListener(
38
type: string,
39
listener: EventListener,
40
options?: AddEventListenerOptions | boolean
41
): void;
42
43
// Toggle state management
44
function useToggle(defaultValue?: boolean): [
45
Ref<boolean>,
46
(value?: boolean) => void
47
];
48
49
// Countdown functionality
50
function useCountDown(options: {
51
time: number;
52
millisecond?: boolean;
53
onChange?: (current: CountDown) => void;
54
onFinish?: () => void;
55
}): {
56
current: ComputedRef<CountDown>;
57
start: () => void;
58
pause: () => void;
59
reset: (totalTime?: number) => void;
60
};
61
62
interface CountDown {
63
total: number;
64
days: number;
65
hours: number;
66
minutes: number;
67
seconds: number;
68
milliseconds: number;
69
}
70
71
// Click outside detection
72
function useClickAway(
73
target: Ref<Element | undefined> | Array<Ref<Element | undefined>>,
74
listener: (event: Event) => void,
75
options?: { eventName?: string }
76
): void;
77
78
// Page visibility detection
79
function usePageVisibility(): Ref<VisibilityState>;
80
81
// Window size tracking
82
function useWindowSize(): {
83
width: Ref<number>;
84
height: Ref<number>;
85
};
86
87
// Custom field value handling
88
function useCustomFieldValue<T>(getValue: () => T): [
89
Ref<T>,
90
(value: T) => void
91
];
92
```
93
94
**Usage Examples:**
95
96
```typescript
97
import { ref, onMounted } from 'vue';
98
import { useRect, useToggle, useCountDown, useClickAway } from 'vant';
99
100
export default {
101
setup() {
102
const elementRef = ref<HTMLElement>();
103
const [visible, toggleVisible] = useToggle(false);
104
105
// Get element dimensions
106
const rect = useRect(elementRef);
107
console.log('Element size:', rect.width, rect.height);
108
109
// Countdown timer
110
const { current, start, pause, reset } = useCountDown({
111
time: 30 * 1000, // 30 seconds
112
onChange: (current) => {
113
console.log('Time remaining:', current.seconds);
114
},
115
onFinish: () => {
116
console.log('Countdown finished!');
117
}
118
});
119
120
// Click outside to close
121
useClickAway(elementRef, () => {
122
toggleVisible(false);
123
});
124
125
return {
126
elementRef,
127
visible,
128
toggleVisible,
129
current,
130
start,
131
pause,
132
reset
133
};
134
}
135
};
136
```
137
138
### Utility Functions
139
140
Core utility functions for common operations and data manipulation.
141
142
```typescript { .api }
143
import {
144
addUnit,
145
createNamespace,
146
isDef,
147
isNumeric,
148
formatNumber,
149
clamp,
150
addNumber,
151
preventDefault,
152
stopPropagation,
153
raf,
154
cancelRaf,
155
getScrollTop,
156
setScrollTop,
157
getRootScrollTop,
158
setRootScrollTop,
159
getElementTop,
160
getVisibleHeight,
161
getVisibleTop,
162
isHidden
163
} from 'vant/es/utils';
164
165
// Add unit to numeric value
166
function addUnit(value?: string | number): string | undefined;
167
168
// Create BEM namespace
169
function createNamespace(name: string): [
170
(modifier?: string) => string,
171
(element?: string, modifier?: string) => string,
172
(element?: string) => string
173
];
174
175
// Type checking utilities
176
function isDef<T>(val: T): val is NonNullable<T>;
177
function isNumeric(val: string): boolean;
178
179
// Number formatting
180
function formatNumber(num: string): string;
181
function clamp(num: number, min: number, max: number): number;
182
function addNumber(num1: number | string, num2: number | string): number;
183
184
// Event utilities
185
function preventDefault(event: Event, isStopPropagation?: boolean): void;
186
function stopPropagation(event: Event): void;
187
188
// Animation frame utilities
189
function raf(fn: FrameRequestCallback): number;
190
function cancelRaf(id: number): void;
191
192
// Scroll utilities
193
function getScrollTop(element?: Element | Window): number;
194
function setScrollTop(element: Element | Window, value: number): void;
195
function getRootScrollTop(): number;
196
function setRootScrollTop(value: number): void;
197
198
// Position utilities
199
function getElementTop(element: Element, scroller?: Element): number;
200
function getVisibleHeight(element: Element): number;
201
function getVisibleTop(element: Element): number;
202
function isHidden(element: Element): boolean;
203
```
204
205
### Component Installation Utilities
206
207
Utilities for component registration and installation.
208
209
```typescript { .api }
210
import { withInstall, withNoopInstall } from 'vant/es/utils';
211
import type { App, Component } from 'vue';
212
213
// Install component with global registration
214
function withInstall<T extends Component>(component: T): T & {
215
install: (app: App) => void;
216
};
217
218
// Install component without registration (for directive-only components)
219
function withNoopInstall<T extends Component>(component: T): T & {
220
install: () => void;
221
};
222
```
223
224
### Touch and Gesture Utilities
225
226
Touch handling utilities for mobile gesture recognition.
227
228
```typescript { .api }
229
import { useTouch } from 'vant';
230
231
function useTouch(): {
232
move: Ref<{ deltaX: number; deltaY: number; offsetX: number; offsetY: number; direction: string }>;
233
start: (event: TouchEvent) => void;
234
move: (event: TouchEvent) => void;
235
reset: () => void;
236
startX: Ref<number>;
237
startY: Ref<number>;
238
deltaX: Ref<number>;
239
deltaY: Ref<number>;
240
offsetX: Ref<number>;
241
offsetY: Ref<number>;
242
direction: Ref<'horizontal' | 'vertical' | ''>;
243
isHorizontal: () => boolean;
244
isVertical: () => boolean;
245
};
246
```
247
248
### Locale and Internationalization
249
250
Utilities for managing translations and locale switching.
251
252
```typescript { .api }
253
import { Locale } from 'vant';
254
255
// Locale management
256
interface LocaleMessages {
257
[key: string]: any;
258
}
259
260
namespace Locale {
261
// Add locale messages
262
function add(messages: LocaleMessages): void;
263
264
// Use specific locale
265
function use(lang: string, messages?: LocaleMessages): void;
266
267
// Get current locale
268
function current(): string;
269
}
270
271
// Built-in language packs available
272
const langs = [
273
'zh-CN', 'zh-TW', 'en-US', 'es-ES', 'de-DE',
274
'fr-FR', 'ja-JP', 'ko-KR', 'ru-RU', 'th-TH',
275
'vi-VN', 'tr-TR', 'pt-BR', 'ar-SA', 'id-ID'
276
];
277
```
278
279
**Usage Example:**
280
281
```typescript
282
import { Locale } from 'vant';
283
import enUS from 'vant/es/locale/lang/en-US';
284
import zhCN from 'vant/es/locale/lang/zh-CN';
285
286
// Switch to English
287
Locale.use('en-US', enUS);
288
289
// Switch to Chinese
290
Locale.use('zh-CN', zhCN);
291
292
// Add custom translations
293
Locale.add({
294
'en-US': {
295
customMessage: 'Custom message in English'
296
},
297
'zh-CN': {
298
customMessage: '中文自定义消息'
299
}
300
});
301
```
302
303
### Configuration and Theme
304
305
Global configuration utilities for theming and customization.
306
307
```typescript { .api }
308
import { ConfigProvider } from 'vant';
309
310
// Theme configuration
311
interface ConfigProviderThemeVars {
312
// Color variables
313
'--van-primary-color'?: string;
314
'--van-success-color'?: string;
315
'--van-danger-color'?: string;
316
'--van-warning-color'?: string;
317
'--van-text-color'?: string;
318
'--van-active-color'?: string;
319
'--van-active-opacity'?: string;
320
'--van-disabled-opacity'?: string;
321
'--van-background-color'?: string;
322
'--van-background-color-light'?: string;
323
'--van-text-color-2'?: string;
324
'--van-text-color-3'?: string;
325
'--van-border-color'?: string;
326
'--van-font-size-xs'?: string;
327
'--van-font-size-sm'?: string;
328
'--van-font-size-md'?: string;
329
'--van-font-size-lg'?: string;
330
'--van-padding-base'?: string;
331
'--van-padding-xs'?: string;
332
'--van-padding-sm'?: string;
333
'--van-padding-md'?: string;
334
'--van-padding-lg'?: string;
335
'--van-padding-xl'?: string;
336
[key: string]: string | undefined;
337
}
338
339
// CSS variable utilities
340
function setCssVar(name: string, value: string, element?: Element): void;
341
function getCssVar(name: string, element?: Element): string;
342
```