目的
- 创建一个管理watcher、computed这样的作用域,以便能够统一|自动卸载依赖
- 可以脱离组件使用,则类似 unmounted 生命周期
使用
const scope = effectScope()
scope.run(() => {
const doubled = computed(() => counter.value * 2)
watch(doubled, () => console.log(doubled.value))
watchEffect(() => console.log('Count: ', doubled.value))
})
scope.stop()
获取当前活跃的effect scope和执行时所处的scope有关
<script setup>
import {effectScope,ref,onScopeDispose,getCurrentScope} from 'vue'
const setupScope=getCurrentScope()
const scope=effectScope();
scope.run(()=>{
const count=ref(0)
getCurrentScope()
onScopeDispose(()=>{
console.log('卸载了3')
})
return {count}
})
function fn(){
getCurrentScope()
}
</script>
<template>
<div @click='fn'></div>
</template>
监听作用域停止
- 会在当前作用域以及上级scop作用域被卸载时调用
- 如果const scope=effectScope(true),那上级作用域销毁时,不会销毁自身,自身作用域内的onScopeDispose不会触发
- 当组件卸载时会自动调用
- 通过scope.stop|getCurrentScope().stop()手动调用
- 每个onScopeDispose只会触发一次
<script setup>
const scope=effectScope();
const s=getCurrentScope(true);
const state=scope.run(()=>{
const count=ref(0)
onScopeDispose(()=>{
console.log('绑定scope卸载')
})
return {count}
})
onScopeDispose(()=>{
console.log('绑定setup scope卸载了')
})
onScopeDispose(()=>{
console.log('绑定setup scope卸载了2')
})
</script>