Open 666p opened 3 months ago
// 你的答案
<script setup lang="ts"> import { ref, computed, watch, watchEffect, effectScope, } from 'vue' const counter = ref( 1 ) const doubled = computed( () => counter.value * 2 ) // 使用 `effectScope` API 使这些Effect效果在触发一次后停止 const scope = effectScope() // 第一种方法,开启监听后立即注销监听 const stop1 = watch( doubled, () => { console.log( 'watch:', doubled.value ) stop1() } ) const stop2 = watchEffect( () => { console.log( 'watchEffect: ', doubled.value ) stop2() }, { flush: 'post' }) // 第二种方法,在下次更新前调用stop方法注销run函数里面的监听方法 scope.run(() => { watch( doubled, () => { console.log( 'watch:', doubled.value ) } ) watchEffect( () => { console.log( 'watchEffect: ', doubled.value ) }) }) counter.value = 2 setTimeout( () => { scope.stop() counter.value = 4 } ) </script> <template> <div> <p> {{ doubled }} </p> </div> </template>