webfansplz / vuejs-challenges

Collection of Vue.js challenges
https://vuejs-challenges.netlify.app/
MIT License
2.7k stars 188 forks source link

8 - Effect作用域 API #2682

Open JJczC-love opened 4 months ago

JJczC-love commented 4 months ago
<script setup lang="ts">
/** scope停止的时机需要在两次监听回调之间,所以不能直接同步关闭 */
import { ref, computed, watch, watchEffect, effectScope, nextTick } from "vue"

const counter = ref(1)
const doubled = computed(() => counter.value * 2)

const scope = effectScope()
scope.run(() => {
  watch(doubled, () => console.log(doubled.value))
  watchEffect(() => console.log(`Count: ${doubled.value}`))
  // 在nextTick内是合理的,完成一个完整的更新队列即停止监听
  nextTick(() => {
    scope.stop()
  })
})

counter.value = 2
counter.value = 4

setTimeout(() => {
  counter.value = 8
}, 100)

</script>

<template>
  <div>
    <p>
      {{ doubled }}
    </p>
  </div>
</template>