vue3中的effectScope有什么作用,如何使用?如何自动清理

vue3中的effectScope有什么作用,如何使用?如何自动清理

vue3中的effectScope有什么作用,如何使用

官网介绍:

创建一个 effect 作用域,可以捕获其中所创建的响应式副作用 (即计算属性和侦听器),这样捕获到的副作用可以一起处理。

作用

scope.run内可创建多个 像watch、watchEffect这种响应式函数,然后通过scope.stop()停止里面的所有响应式函数。

批量管理副作用: 可以把多个 effect 函数放到一个 effectScope 里,然后通过 effectScope.stop() 方法一次性停止所有这些副作用函数的运行。
组件卸载时清理副作用: 在组件卸载时,使用 effectScope 能够更方便地清理所有相关的副作用,避免内存泄漏。
支持嵌套作用域

特点

  • Vue 3.2+ 新增的 API
  • 主要用于组织和批量管理 effect
  • 特别适合在组件 setup 中使用
  • 支持自动清理

简单示例:

html 复制代码
<script setup lang="ts">
  import { effectScope, reactive, watch, watchEffect } from 'vue';

  const scope = effectScope();

  const state = reactive({ count: 0 });
  scope.run(() => {
    // 这些 effect 都会被 scope 管理
    watch(
      () => state.count,
      (count) => {
        console.log('effectScope管理的watch监听:', count);
      }
    );
    watchEffect(() => {
      console.log('effectScope管理的watchEffect监听', state.count);
    });
  });

  // 停止所有 effect,会将上面的watch和watchEffect都停止。
  const handleStop = () => {
    scope.stop();
  };

// 自己调用watch监听
  const singleWatch = watch(
    () => state.count,
    (count) => {
      console.log('单个监听watch:', count);
    }
  );
  // 停止自己创建的watch监听
  const handleStopWatch = () => {
    singleWatch();
  };
</script>

<template>
  <a-button @click="state.count++">count:{{ state.count }}</a-button>
  <a-button @click="handleStop">停止</a-button>
  <a-button @click="handleStopWatch">停止 watch</a-button>
</template>

<style scoped lang="less"></style>

自动清理示例

使用onScopeDispose实现组件卸载时自动,自动清理effectScope

js 复制代码
import { effectScope, onScopeDispose } from 'vue'

export default {
  setup() {
    const scope = effectScope()
    
    scope.run(() => {
      // 所有响应式逻辑
      const state = reactive({ /*...*/ })
      watch(/*...*/)
      computed(/*...*/)
    })
    
    onScopeDispose(() => {
      scope.stop() // 组件卸载时自动清理
    })
    
    return {}
  }
}
相关推荐
科研邪修法1 小时前
PDF新增页面文字与文本批注怎么区分?以双版本培训讲义为例
前端·css·pdf
武昌库里写JAVA1 小时前
SpringBoot+Vue 项目介绍
java·javascript·git·sql·ai
Lanwarf-前端开发3 小时前
Vue3 + Canvas/WebGL 雷达扫描可视化实战:PPI、RHI、VOL、SVOL 四种模式原理与实现
前端·javascript·vue.js·webgl
FRing033 小时前
vue3干货总结2(vue3生命周期、父子通信、模版引用、provide和inject)
开发语言·前端·vue.js·vue3
锋行天下5 小时前
langgraph 全栈项目(三)
前端·人工智能·后端
YIAN5 小时前
从 LangChain 到 DeepAgents:手把手拆解 createAgent、Middleware 与复杂 Agent
javascript·langchain·deepseek
锋行天下6 小时前
langgraph 全栈项目(二)
前端·人工智能·后端
冬夜Zis7 小时前
顺着作用域链和 outer 指针,一次性看懂闭包底层逻辑
javascript
Ceelog7 小时前
Mac 上怎么找出并安全清理旧的 node_modules?(实测 304 个占 66.3 GB)
javascript