javascript / intermediate
Snippet
Automated Side-Effect Cleanup with onScopeDispose
onScopeDispose is a lifecycle hook that executes when the current reactive scope is destroyed. It is ideal for cleaning up manual subscriptions or timers without being tethered to a specific component instance.
snippet.js
1
2
3
4
5
6
7
8
9
import { onScopeDispose } from 'vue';export function useExternalService(service) {service.connect();onScopeDispose(() => {service.disconnect();});}
vue
Breakdown
1
import { onScopeDispose } from 'vue';
Imports the hook that manages scope-level cleanup.
2
onScopeDispose(() => { ... });
Registers a callback to run when the effect scope or component is unmounted.