effectScope()
Official explanation: Create an effect scope to capture the reactive side effects (i.e. computed properties and listeners) created in it, so that the captured side effects can be processed together .
Personal understanding: Call it Listening Butler to be more vivid. In layman's terms, it can manage computed properties and listeners in a function, and then stop listening uniformly.
Code example:
// 定义侦听管家实例
const scope = effectScope()
scope.run(() => {
// 把计算属性、监听事件放置在这里
const doubled = computed(() => counter.value * 2)
watch(doubled, () => console.log(doubled.value))
watchEffect(() => console.log('Count: ', doubled.value))
})
// 处理掉当前作用域内的所有 effect
scope.stop() //停止监听
getCurrentScope()
Description: Get the current listening butler instance.
For example, if there are multiple housekeepers on a page, and we don’t want to cancel the monitoring of each housekeeper one by one, we can cancel the monitoring in batches in this way.
allScope.stop() // Cancel all listening housekeeper monitoring
Code example:
const allScope = getCurrentScope()
allScope.stop() // 取消所有侦听管家监听
onScopeDispose()
Description: This is a callback event. Triggered when getCurrentScope().stop() is executed, or when the component logs out.
prototype:
onScopeDispose(()=>{
// to do...
})
Examples illustrate the application of all three:
<script setup>
import {
ref,
computed,
watch,
watchEffect,
effectScope,
getCurrentScope,
onScopeDispose
} from 'vue'
const counter = ref(2)
// 定义第一个侦听管家
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() // 调用它,可以取消scope内的侦听。执行这个不会触发onScopeDispose事件
// 定义第二个侦听管家
const scope2 = effectScope()
scope2.run(() => {
const doubled2 = computed(() => counter.value * 3)
watch(doubled2, () => console.log(doubled2.value))
watchEffect(() => console.log('Count: ', doubled2.value))
})
//scope2.stop() // 调用它,可以取消scope2内的侦听。执行这个不会触发onScopeDispose事件
// 获取当前侦听实例
const allScope = getCurrentScope()
// 执行 allScope.stop()时会触发 onScopeDispose 事件
// 当前页面或组件注销时会触发 onScopeDispose 事件
onScopeDispose(() => {
console.log('已停止所有侦听');
// to do...
})
// 5秒后停止所有侦听,此时会触发 onScopeDispose 事件
setTimeout(() => {
allScope.stop()
}, 5000)
</script>