vue3中的effectScope有什么作用,如何使用?如何自动清理
vue3中的effectScope有什么作用,如何使用?如何自动清理
vue3中的effectScope有什么作用,如何使用
- 官网介绍:
- 作用
- 特点
- 简单示例:
- 自动清理示例
官网介绍:
创建一个 effect 作用域,可以捕获其中所创建的响应式副作用 (即计算属性和侦听器),这样捕获到的副作用可以一起处理。
作用
scope.run
内可创建多个 像watch
、watchEffect
这种响应式函数,然后通过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 {}}
}