watchEffect tự động track dependencies và re-run khi chúng thay đổi.
Có các tùy chọn nâng cao:
typescript
import { watchEffect, ref } from 'vue'
const userId = ref(1)
const userData = ref(null)
// Cleanup function — cancel previous async operation
const stop = watchEffect(async (onCleanup) => {
let cancelled = false
onCleanup(() => {
cancelled = true // Được gọi trước khi effect chạy lại
})
const data = await fetch(`/api/users/${userId.value}`).then(r => r.json())
if (!cancelled) {
userData.value = data // Chỉ update nếu request này vẫn relevant
}
})
// Stop watcher thủ công
stop() // Dừng watching — cleanup memory leak
// Flush timing
watchEffect(() => {
// Mặc định: pre-flush — chạy trước DOM update
}, { flush: 'post' }) // post: chạy sau DOM update
// watchPostEffect và watchSyncEffect — syntactic sugar
import { watchPostEffect, watchSyncEffect } from 'vue'
watchPostEffect(() => { /* chạy sau DOM update */ })Dùng cleanup cho: cancel fetch requests, clear timers, cancel WebSocket subscriptions khi dependency thay đổi.