0
# Lifecycle Hooks
1
2
Function-based lifecycle hooks that integrate with Vue 2's component lifecycle system. These hooks allow you to execute code at specific points in the component lifecycle within the setup function.
3
4
## Capabilities
5
6
### Basic Lifecycle Hooks
7
8
Core lifecycle hooks that correspond to Vue 2's component lifecycle options.
9
10
```typescript { .api }
11
/**
12
* Registers a callback to be called before the component is mounted
13
* @param hook - Callback function to execute
14
* @param target - Target component instance (optional)
15
* @returns Cleanup function or undefined
16
*/
17
function onBeforeMount(hook: () => void, target?: ComponentInternalInstance): Function | undefined;
18
19
/**
20
* Registers a callback to be called after the component is mounted
21
* @param hook - Callback function to execute
22
* @param target - Target component instance (optional)
23
* @returns Cleanup function or undefined
24
*/
25
function onMounted(hook: () => void, target?: ComponentInternalInstance): Function | undefined;
26
27
/**
28
* Registers a callback to be called before the component updates
29
* @param hook - Callback function to execute
30
* @param target - Target component instance (optional)
31
* @returns Cleanup function or undefined
32
*/
33
function onBeforeUpdate(hook: () => void, target?: ComponentInternalInstance): Function | undefined;
34
35
/**
36
* Registers a callback to be called after the component updates
37
* @param hook - Callback function to execute
38
* @param target - Target component instance (optional)
39
* @returns Cleanup function or undefined
40
*/
41
function onUpdated(hook: () => void, target?: ComponentInternalInstance): Function | undefined;
42
43
/**
44
* Registers a callback to be called before the component is unmounted
45
* @param hook - Callback function to execute
46
* @param target - Target component instance (optional)
47
* @returns Cleanup function or undefined
48
*/
49
function onBeforeUnmount(hook: () => void, target?: ComponentInternalInstance): Function | undefined;
50
51
/**
52
* Registers a callback to be called after the component is unmounted
53
* @param hook - Callback function to execute
54
* @param target - Target component instance (optional)
55
* @returns Cleanup function or undefined
56
*/
57
function onUnmounted(hook: () => void, target?: ComponentInternalInstance): Function | undefined;
58
```
59
60
**Usage Examples:**
61
62
```typescript
63
import {
64
ref,
65
onBeforeMount,
66
onMounted,
67
onBeforeUpdate,
68
onUpdated,
69
onBeforeUnmount,
70
onUnmounted
71
} from "@vue/composition-api";
72
73
export default {
74
setup() {
75
const count = ref(0);
76
const element = ref<HTMLElement | null>(null);
77
78
onBeforeMount(() => {
79
console.log("Component is about to be mounted");
80
// DOM is not available yet
81
});
82
83
onMounted(() => {
84
console.log("Component has been mounted");
85
// DOM is available
86
if (element.value) {
87
element.value.focus();
88
}
89
});
90
91
onBeforeUpdate(() => {
92
console.log("Component is about to update");
93
// DOM still reflects old values
94
});
95
96
onUpdated(() => {
97
console.log("Component has been updated");
98
// DOM reflects new values
99
});
100
101
onBeforeUnmount(() => {
102
console.log("Component is about to be unmounted");
103
// Cleanup subscriptions, timers, etc.
104
});
105
106
onUnmounted(() => {
107
console.log("Component has been unmounted");
108
// Final cleanup
109
});
110
111
return {
112
count,
113
element,
114
};
115
},
116
};
117
```
118
119
### Error Handling Hook
120
121
Hook for capturing and handling errors in child components.
122
123
```typescript { .api }
124
/**
125
* Registers a callback to be called when an error is captured from a child component
126
* @param hook - Error handling callback
127
*/
128
function onErrorCaptured(
129
hook: (error: Error, instance: ComponentInstance, info: string) => boolean | void,
130
target?: ComponentInternalInstance
131
): Function | undefined;
132
```
133
134
**Usage Examples:**
135
136
```typescript
137
import { onErrorCaptured } from "@vue/composition-api";
138
139
export default {
140
setup() {
141
onErrorCaptured((error, instance, info) => {
142
console.error("Error captured:", error);
143
console.log("Error info:", info);
144
console.log("Component instance:", instance);
145
146
// Return false to prevent the error from propagating further
147
return false;
148
});
149
150
return {};
151
},
152
};
153
```
154
155
### Keep-Alive Hooks
156
157
Hooks for components wrapped in keep-alive, handling activation and deactivation.
158
159
```typescript { .api }
160
/**
161
* Registers a callback to be called when a kept-alive component is activated
162
* @param hook - Callback function to execute
163
* @param target - Target component instance (optional)
164
* @returns Cleanup function or undefined
165
*/
166
function onActivated(hook: () => void, target?: ComponentInternalInstance): Function | undefined;
167
168
/**
169
* Registers a callback to be called when a kept-alive component is deactivated
170
* @param hook - Callback function to execute
171
* @param target - Target component instance (optional)
172
* @returns Cleanup function or undefined
173
*/
174
function onDeactivated(hook: () => void, target?: ComponentInternalInstance): Function | undefined;
175
```
176
177
**Usage Examples:**
178
179
```typescript
180
import { ref, onActivated, onDeactivated } from "@vue/composition-api";
181
182
export default {
183
setup() {
184
const isActive = ref(false);
185
186
onActivated(() => {
187
console.log("Component activated");
188
isActive.value = true;
189
// Resume timers, subscriptions, etc.
190
});
191
192
onDeactivated(() => {
193
console.log("Component deactivated");
194
isActive.value = false;
195
// Pause timers, subscriptions, etc.
196
});
197
198
return {
199
isActive,
200
};
201
},
202
};
203
```
204
205
### Server-Side Rendering Hook
206
207
Hook for server-side rendering operations that need to be performed before the component is rendered.
208
209
```typescript { .api }
210
/**
211
* Registers a callback to be called during server-side rendering
212
* @param hook - Async callback function for server prefetch operations
213
*/
214
function onServerPrefetch(hook: () => Promise<any> | void, target?: ComponentInternalInstance): Function | undefined;
215
```
216
217
**Usage Examples:**
218
219
```typescript
220
import { ref, onServerPrefetch } from "@vue/composition-api";
221
222
export default {
223
setup() {
224
const data = ref(null);
225
226
onServerPrefetch(async () => {
227
// This runs only on the server during SSR
228
console.log("Prefetching data on server");
229
230
try {
231
const response = await fetch("/api/initial-data");
232
data.value = await response.json();
233
} catch (error) {
234
console.error("Failed to prefetch data:", error);
235
}
236
});
237
238
return {
239
data,
240
};
241
},
242
};
243
```
244
245
### Advanced Lifecycle Patterns
246
247
Complex patterns for lifecycle management including cleanup, async operations, and resource management.
248
249
**Resource Management:**
250
251
```typescript
252
import { ref, onMounted, onBeforeUnmount } from "@vue/composition-api";
253
254
export default {
255
setup() {
256
const websocket = ref<WebSocket | null>(null);
257
const isConnected = ref(false);
258
259
onMounted(() => {
260
// Initialize WebSocket connection
261
websocket.value = new WebSocket("wss://api.example.com/socket");
262
263
websocket.value.onopen = () => {
264
isConnected.value = true;
265
console.log("WebSocket connected");
266
};
267
268
websocket.value.onmessage = (event) => {
269
console.log("Received message:", event.data);
270
};
271
272
websocket.value.onclose = () => {
273
isConnected.value = false;
274
console.log("WebSocket disconnected");
275
};
276
});
277
278
onBeforeUnmount(() => {
279
// Clean up WebSocket connection
280
if (websocket.value) {
281
websocket.value.close();
282
websocket.value = null;
283
}
284
});
285
286
return {
287
isConnected,
288
};
289
},
290
};
291
```
292
293
**Timer Management:**
294
295
```typescript
296
import { ref, onMounted, onBeforeUnmount } from "@vue/composition-api";
297
298
export default {
299
setup() {
300
const time = ref(new Date());
301
let timer: NodeJS.Timeout | null = null;
302
303
onMounted(() => {
304
// Start timer
305
timer = setInterval(() => {
306
time.value = new Date();
307
}, 1000);
308
});
309
310
onBeforeUnmount(() => {
311
// Clean up timer
312
if (timer) {
313
clearInterval(timer);
314
timer = null;
315
}
316
});
317
318
return {
319
time,
320
};
321
},
322
};
323
```
324
325
**Event Listener Management:**
326
327
```typescript
328
import { ref, onMounted, onBeforeUnmount } from "@vue/composition-api";
329
330
export default {
331
setup() {
332
const windowWidth = ref(window.innerWidth);
333
334
const handleResize = () => {
335
windowWidth.value = window.innerWidth;
336
};
337
338
onMounted(() => {
339
window.addEventListener("resize", handleResize);
340
});
341
342
onBeforeUnmount(() => {
343
window.removeEventListener("resize", handleResize);
344
});
345
346
return {
347
windowWidth,
348
};
349
},
350
};
351
```
352
353
**Async Data Loading:**
354
355
```typescript
356
import { ref, onMounted } from "@vue/composition-api";
357
358
export default {
359
setup() {
360
const data = ref(null);
361
const loading = ref(false);
362
const error = ref(null);
363
364
onMounted(async () => {
365
loading.value = true;
366
error.value = null;
367
368
try {
369
const response = await fetch("/api/data");
370
if (!response.ok) {
371
throw new Error(`HTTP error! status: ${response.status}`);
372
}
373
data.value = await response.json();
374
} catch (err) {
375
error.value = err;
376
console.error("Failed to load data:", err);
377
} finally {
378
loading.value = false;
379
}
380
});
381
382
return {
383
data,
384
loading,
385
error,
386
};
387
},
388
};
389
```
390
391
### Multiple Hook Registration
392
393
You can register multiple callbacks for the same lifecycle hook, and they will be called in the order they were registered.
394
395
```typescript
396
import { ref, onMounted, onBeforeUnmount } from "@vue/composition-api";
397
398
export default {
399
setup() {
400
const analytics = ref(null);
401
const metrics = ref(null);
402
403
// First onMounted callback
404
onMounted(() => {
405
console.log("Initializing analytics");
406
analytics.value = initializeAnalytics();
407
});
408
409
// Second onMounted callback
410
onMounted(() => {
411
console.log("Starting metrics collection");
412
metrics.value = startMetrics();
413
});
414
415
// Multiple cleanup callbacks
416
onBeforeUnmount(() => {
417
if (analytics.value) {
418
analytics.value.shutdown();
419
}
420
});
421
422
onBeforeUnmount(() => {
423
if (metrics.value) {
424
metrics.value.stop();
425
}
426
});
427
428
return {
429
analytics,
430
metrics,
431
};
432
},
433
};
434
```
435
436
## Types
437
438
```typescript { .api }
439
type ComponentInstance = any; // Vue 2 component instance
440
441
interface LifecycleHook {
442
(hook: Function, target?: ComponentInternalInstance | null): Function | undefined;
443
}
444
445
interface ComponentInternalInstance {
446
proxy: ComponentInstance | null;
447
setupState: Record<string, any>;
448
ctx: Record<string, any>;
449
scope: EffectScope;
450
}
451
```