vue3-effectScope

4 阅读1分钟

effectScoped


import {effect, watchEffect, computed, effectScope} from 'vue'


const stopWatch = watch(props.data, () => {})


const stopWatch1 = watchEffect(() => {})


const {effect:ef} = effect(() => {})

const cleanUp =   [stopWatch, stopWatch1, ef.stop]

btn.onclick = () => {cleanUp.forEach((stopEf) => {stopEf()})}
// 这是一种方式去取消effect的监听。

//借助于effectScope

const scope = effectScope();
const _scope = effectScope(true)
scope.run(() => {
    watch(props.data, () => {});
    const stopWatch1 = watchEffect(() => {});
    const {effect:ef} = effect(() => {})
    _scope.run(() => {})
})

scope.stop()
// 只要在scoped 里面运行的 watch watchEFFect computed 这些在调用scope.stop,都会被暂停监听。
对于const scope = effectScoped(); 传递true,表示不递归处理内部嵌套的scope, 只处理外层的