4 min read
•Question 5 of 37mediumWhat are Watchers in Vue?
Understanding watch and watchEffect.
What You'll Learn
- watch function
- watchEffect function
- When to use each
watch()
Explicitly watch specific sources.
code.jsJavaScript
import { ref, watch } from 'vue'
const count = ref(0)
// Watch single ref
watch(count, (newValue, oldValue) => {
console.log(`Count changed from ${oldValue} to ${newValue}`)
})
// Watch with options
watch(count, (newValue) => {
console.log(newValue)
}, { immediate: true, deep: true })watchEffect()
Auto-tracks dependencies.
code.jsJavaScript
import { ref, watchEffect } from 'vue'
const count = ref(0)
const name = ref('Vue')
// Automatically tracks count and name
watchEffect(() => {
console.log(`Count: ${count.value}, Name: ${name.value}`)
})Comparison
| watch | watchEffect |
|---|---|
| Explicit sources | Auto-tracks |
| Access old value | No old value |
| Lazy by default | Runs immediately |
| More control | Less boilerplate |
Cleanup
code.jsJavaScript
watchEffect((onCleanup) => {
const timer = setInterval(() => {}, 1000)
onCleanup(() => {
clearInterval(timer)
})
})