Build Vue's effectScope(): nested and detached scopes, onScopeDispose, pause and resume, and a shared composable
Problem
Every component in Vue 3 owns an effect scope. The effects and watchers created during setup() attach to it, and unmounting the component stops the scope, which stops all of them at once. The same API is public as effectScope(), and libraries such as VueUse use it to run composables outside components without leaking watchers. Build it on top of the small reactivity core in the starter.
const scope = effectScope();
const count = ref(0);
scope.run(() => {
watch(count, (n) => console.log("count", n));
onScopeDispose(() => console.log("disposed"));
});
count.value = 1; // logs "count 1"
scope.stop(); // logs "disposed"
count.value = 2; // nothing: the watcher is stoppedRef. UR-1460 · © UIRound · uiround.com/questions/build-vues-effectscope-nested-and-detached-scopes-onscopedispose-pause-and-resume-and-a-shared-composable
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 4
- code listings
- 7
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1A scope is a bag of three lists: effects, cleanup functions and child scopes. Keep one module-level
activeEffectScope;run(fn)swaps it in, callsfnand swaps the previous one back in afinally. Effects and child scopes attach themselves to whatever scope is active when they are created.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.