已停止的EffectScope实例能否重新运行?是否支持多次启停?
EffectScope 实例停止后能否重新运行及多次启停?
- 已停止的EffectScope实例无法重新运行:调用
scope.stop()后,该作用域内所有响应式副作用(如watch、effect)会被永久终止,内部依赖追踪链路被清理,后续调用scope.run()不会产生任何效果。 - 不支持对同一作用域实例进行多次运行与停止:EffectScope设计为一次性使用,一旦停止就进入失效状态,无法复用。
你的代码问题分析
你当前的代码中,当msg长度≤1时调用scope.stop(),这个scope就彻底失效了。之后即使msg长度再次大于1,调用scope.run()也不会更新test.value,因为该作用域已经无法再管理任何副作用。
实现类似"多次启停"的正确方式
如果需要按需启用/停止副作用,应该每次启用时创建新的EffectScope实例,停止时销毁当前实例:
<script setup> import { ref, effectScope, watch } from 'vue' const msg = ref('Hello World!') const test = ref(msg.value.length) let activeScope = null watch(msg, value => { // 先清理之前的作用域 if (activeScope) { activeScope.stop() activeScope = null } if (value.length > 1) { // 创建新作用域并运行副作用 activeScope = effectScope(false) activeScope.run(() => { test.value = msg.value.length // 这里可以添加其他需要管控的副作用,比如监听msg变化 // watch(msg, val => test.value = val.length) }) } else { test.value = value.length } }) </script> <template> <h1>{{ msg }}</h1> <h2>{{ test }}</h2> <input v-model="msg" /> </template>
这种方式通过维护一个activeScope变量,每次需要启用副作用时创建新实例,停止时销毁旧实例,从而实现类似"多次启停"的效果。
内容的提问来源于stack exchange,提问作者Boris
相关产品推荐
相关产品推荐

