欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > vue3中的effectScope有什么作用,如何使用?如何自动清理

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

2025/4/28 9:42:57 来源:https://blog.csdn.net/qq_32442967/article/details/147516686  浏览:    关键词:vue3中的effectScope有什么作用,如何使用?如何自动清理

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

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

    • 官网介绍:
    • 作用
    • 特点
    • 简单示例:
    • 自动清理示例

官网介绍:

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

作用

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

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

特点

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

简单示例:

<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

import { effectScope, onScopeDispose } from 'vue'export default {setup() {const scope = effectScope()scope.run(() => {// 所有响应式逻辑const state = reactive({ /*...*/ })watch(/*...*/)computed(/*...*/)})onScopeDispose(() => {scope.stop() // 组件卸载时自动清理})return {}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词