Function hook watchEffect()
Runs a function immediately while reactively
tracking its dependencies and re-runs it whenever
the dependencies are changed.
function watchEffect(
effect: (onCleanup: OnCleanup) => void,
options?: WatchEffectOptions
): StopHandle
type OnCleanup = (cleanupFn: () => void) => void
interface WatchEffectOptions {
flush?: 'pre' | 'post' | 'sync' // default: 'pre'
onTrack?: (event: DebuggerEvent) => void
onTrigger?: (event: DebuggerEvent) => void
}
type StopHandle = () => void
const count = ref(0)
watchEffect(() => console.log(count.value))
// -> logs 0
count.value++
// -> logs 1
watchEffect(async (onCleanup) => {
const { response, cancel } = doAsyncWork(id.value)
// `cancel` will be called if `id` changes
// so that previous pending request will be cancelled
// if not yet completed
onCleanup(cancel)
data.value = await response
})
const stop = watchEffect(() => {})
// when the watcher is no longer needed:
stop()