Skip to content

Commit 373d3cd

Browse files
committed
effectScope
1 parent 8c7cabe commit 373d3cd

File tree

3 files changed

+62
-1
lines changed

3 files changed

+62
-1
lines changed

src/.vuepress/config.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,8 @@ const sidebar = {
154154
children: [
155155
'/api/basic-reactivity',
156156
'/api/refs-api',
157-
'/api/computed-watch-api'
157+
'/api/computed-watch-api',
158+
'/api/effect-scope',
158159
]
159160
},
160161
'/api/composition-api',

src/api/effect-scope.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Effect Scope API <Badge text="3.2+" />
2+
3+
:::info
4+
Effect scope is an advanced API primarily intended for library authors. For details on how to leverage this API, please consult its corresponding [RFC](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0041-reactivity-effect-scope.md).
5+
:::
6+
7+
## `effectScope`
8+
9+
Creates an effect scope object which can capture the reactive effects (e.g. computed and watchers) created within it so that these effects can be disposed together.
10+
11+
**Typing:**
12+
13+
```ts
14+
function effectScope(detached?: boolean): EffectScope
15+
16+
interface EffectScope {
17+
run<T>(fn: () => T): T | undefined // undefined if scope is inactive
18+
stop(): void
19+
}
20+
```
21+
22+
**Example:**
23+
24+
```js
25+
const scope = effectScope()
26+
27+
scope.run(() => {
28+
const doubled = computed(() => counter.value * 2)
29+
30+
watch(doubled, () => console.log(doubled.value))
31+
32+
watchEffect(() => console.log('Count: ', doubled.value))
33+
})
34+
35+
// to dispose all effects in the scope
36+
scope.stop()
37+
```
38+
39+
## `getCurrentScope`
40+
41+
Returns the current active [effect scope](#effectscope) if there is one.
42+
43+
**Typing:**
44+
45+
```ts
46+
function getCurrentScope(): EffectScope | undefined
47+
```
48+
49+
## `onScopeDispose`
50+
51+
Registers a dispose callback on the current active [effect scope](#effectscope). The callback will be invoked when the associated effect scope is stopped.
52+
53+
This method can be used as a non-component-coupled replacement of `onUnmounted` in reusable composition functions, since each Vue component's `setup()` function is also invoked in an effect scope.
54+
55+
**Typing:**
56+
57+
```ts
58+
function onScopeDispose(fn: () => void): void
59+
```

src/api/reactivity-api.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@ The Reactivity API contains the following sections:
55
- [Basic Reactivity APIs](/api/basic-reactivity.html)
66
- [Refs](/api/refs-api.html)
77
- [Computed and watch](/api/computed-watch-api.html)
8+
- [Effect Scope API](/api/effect-scope.html)

0 commit comments

Comments
 (0)