0
# Event Handling
1
2
Event listener management with automatic cleanup and specialized event utilities for common interaction patterns.
3
4
## Capabilities
5
6
### Event Listeners
7
8
#### useEventListener
9
10
Register event listeners with automatic cleanup and flexible target support.
11
12
```typescript { .api }
13
/**
14
* Register event listener with automatic cleanup
15
* @param target - Event target (window, document, element, or ref)
16
* @param event - Event name
17
* @param listener - Event listener function
18
* @param options - Event listener options
19
* @returns Stop function
20
*/
21
function useEventListener<E extends keyof WindowEventMap>(
22
event: E,
23
listener: (this: Window, ev: WindowEventMap[E]) => any,
24
options?: ConfigurableWindow & AddEventListenerOptions
25
): Fn;
26
27
function useEventListener<E extends keyof DocumentEventMap>(
28
target: Document,
29
event: E,
30
listener: (this: Document, ev: DocumentEventMap[E]) => any,
31
options?: AddEventListenerOptions
32
): Fn;
33
34
function useEventListener<E extends keyof HTMLElementEventMap>(
35
target: MaybeElementRef,
36
event: E,
37
listener: (this: HTMLElement, ev: HTMLElementEventMap[E]) => any,
38
options?: AddEventListenerOptions
39
): Fn;
40
41
function useEventListener(
42
target: MaybeElementRef,
43
event: string,
44
listener: EventListener,
45
options?: AddEventListenerOptions
46
): Fn;
47
```
48
49
**Usage Examples:**
50
51
```typescript
52
import { ref } from "vue";
53
import { useEventListener } from "@vueuse/core";
54
55
// Window events
56
useEventListener('resize', () => {
57
console.log('Window resized');
58
});
59
60
// Document events
61
useEventListener(document, 'visibilitychange', () => {
62
console.log('Visibility changed:', document.visibilityState);
63
});
64
65
// Element events
66
const button = ref<HTMLButtonElement>();
67
useEventListener(button, 'click', (e) => {
68
console.log('Button clicked:', e);
69
});
70
71
// Custom events
72
useEventListener('my-custom-event', (e) => {
73
console.log('Custom event:', e.detail);
74
});
75
76
// With options
77
useEventListener('scroll', handleScroll, {
78
passive: true,
79
capture: true
80
});
81
```
82
83
#### useEventBus
84
85
Event bus for component communication.
86
87
```typescript { .api }
88
/**
89
* Event bus for component communication
90
* @param key - Optional bus key for multiple buses
91
* @returns Event bus utilities
92
*/
93
function useEventBus<T = unknown, P = T>(key?: any): UseEventBusReturn<T, P>;
94
95
interface UseEventBusReturn<T, P> {
96
on: (listener: (event: T) => void) => Fn;
97
once: (listener: (event: T) => void) => Fn;
98
off: (listener: (event: T) => void) => void;
99
emit: (event?: P) => void;
100
reset: () => void;
101
}
102
```
103
104
### Click Events
105
106
#### onClickOutside
107
108
Listen for clicks outside of an element with ignore list support.
109
110
```typescript { .api }
111
/**
112
* Listen for clicks outside of an element
113
* @param target - Target element or ref
114
* @param handler - Click outside handler
115
* @param options - Configuration options
116
* @returns Stop function
117
*/
118
function onClickOutside(
119
target: MaybeElementRef,
120
handler: OnClickOutsideHandler,
121
options?: OnClickOutsideOptions
122
): Fn;
123
124
interface OnClickOutsideOptions extends ConfigurableWindow {
125
ignore?: (MaybeElementRef | string)[];
126
capture?: boolean;
127
detectIframe?: boolean;
128
}
129
130
type OnClickOutsideHandler = (evt: PointerEvent) => void;
131
```
132
133
**Usage Examples:**
134
135
```typescript
136
import { ref } from "vue";
137
import { onClickOutside } from "@vueuse/core";
138
139
const modal = ref<HTMLElement>();
140
const isOpen = ref(false);
141
142
onClickOutside(modal, () => {
143
isOpen.value = false;
144
});
145
146
// With ignore list
147
const trigger = ref<HTMLElement>();
148
onClickOutside(modal, () => {
149
isOpen.value = false;
150
}, {
151
ignore: [trigger]
152
});
153
```
154
155
### Keyboard Events
156
157
#### onKeyStroke
158
159
Listen for specific key strokes with modifier support.
160
161
```typescript { .api }
162
/**
163
* Listen for key strokes with modifier support
164
* @param key - Key or keys to listen for
165
* @param handler - Key stroke handler
166
* @param options - Configuration options
167
* @returns Stop function
168
*/
169
function onKeyStroke(
170
key: KeyFilter,
171
handler: (event: KeyboardEvent) => void,
172
options?: OnKeyStrokeOptions
173
): Fn;
174
175
interface OnKeyStrokeOptions {
176
eventName?: 'keydown' | 'keypress' | 'keyup';
177
target?: MaybeElementRef;
178
passive?: boolean;
179
dedupe?: boolean;
180
}
181
182
type KeyFilter = string | string[] | ((event: KeyboardEvent) => boolean);
183
```
184
185
#### onStartTyping
186
187
Fire when users start typing on non-input elements.
188
189
```typescript { .api }
190
/**
191
* Fire when users start typing on non-input elements
192
* @param callback - Callback when typing starts
193
* @param options - Configuration options
194
* @returns Stop function
195
*/
196
function onStartTyping(
197
callback: (event: KeyboardEvent) => void,
198
options?: OnStartTypingOptions
199
): Fn;
200
201
interface OnStartTypingOptions {
202
document?: Document;
203
}
204
```
205
206
### Advanced Keyboard
207
208
#### useMagicKeys
209
210
Reactive key combination detection with magic key support.
211
212
```typescript { .api }
213
/**
214
* Reactive key combination detection
215
* @param options - Configuration options
216
* @returns Reactive key states
217
*/
218
function useMagicKeys(options?: UseMagicKeysOptions): MagicKeysReturn;
219
220
interface MagicKeysReturn {
221
current: Set<string>;
222
[key: string]: Ref<boolean> | Set<string>;
223
224
// Special combinations
225
ctrl_a: Ref<boolean>;
226
shift_ctrl_a: Ref<boolean>;
227
// ... many more combinations
228
}
229
230
interface UseMagicKeysOptions {
231
reactive?: boolean;
232
target?: MaybeElementRef;
233
aliasMap?: Record<string, string>;
234
passive?: boolean;
235
onEventFired?: (e: KeyboardEvent) => void;
236
}
237
```
238
239
#### useKeyModifier
240
241
Track individual key modifier states.
242
243
```typescript { .api }
244
/**
245
* Track individual key modifier states
246
* @param modifier - Modifier key to track
247
* @param options - Configuration options
248
* @returns Reactive modifier state
249
*/
250
function useKeyModifier(
251
modifier: UseKeyModifierModifier,
252
options?: UseKeyModifierOptions
253
): Ref<boolean>;
254
255
type UseKeyModifierModifier = 'Alt' | 'AltGraph' | 'CapsLock' | 'Control' | 'Fn' | 'Meta' | 'NumLock' | 'ScrollLock' | 'Shift' | 'Symbol' | 'SymbolLock';
256
257
interface UseKeyModifierOptions {
258
events?: UseKeyModifierEvents[];
259
initial?: boolean;
260
}
261
262
type UseKeyModifierEvents = 'mousedown' | 'mouseup' | 'keydown' | 'keyup' | 'pointerdown' | 'pointerup' | 'contextmenu';
263
```
264
265
### Long Press
266
267
#### onLongPress
268
269
Detect long press gestures on elements.
270
271
```typescript { .api }
272
/**
273
* Detect long press gestures
274
* @param target - Target element or ref
275
* @param handler - Long press handler
276
* @param options - Configuration options
277
* @returns Stop function
278
*/
279
function onLongPress(
280
target: MaybeElementRef,
281
handler: (evt: PointerEvent) => void,
282
options?: OnLongPressOptions
283
): () => void;
284
285
interface OnLongPressOptions {
286
delay?: number;
287
modifiers?: OnLongPressModifiers;
288
distanceThreshold?: number | false;
289
}
290
291
interface OnLongPressModifiers {
292
stop?: boolean;
293
once?: boolean;
294
prevent?: boolean;
295
capture?: boolean;
296
self?: boolean;
297
}
298
```