Vue — watch()
Basic watcher
<template>
<div>
<input v-model="question" placeholder="Ask a question">
<p>{{ answer }}</p>
</div>
</template>
<script>
export default {
data() {
return {
question: '',
answer: 'Waiting for a question...'
}
},
watch: {
question(newVal) {
if (newVal.includes('?')) {
this.getAnswer()
}
}
},
methods: {
async getAnswer() {
this.answer = 'Thinking...'
try {
const res = await fetch('https://yesno.wtf/api')
this.answer = (await res.json()).answer
} catch {
this.answer = 'Error. Try again.'
}
}
}
}
</script>
Immediate watcher
<script>
export default {
data() {
return { count: 0 }
},
watch: {
count: {
immediate: true,
handler(newVal) {
console.log('Count changed:', newVal)
}
}
}
}
</script>
Deep watcher
<script>
export default {
data() {
return {
user: {
name: 'John',
address: {
city: 'NYC'
}
}
}
},
watch: {
user: {
deep: true,
handler(newVal) {
console.log('User changed:', newVal)
}
}
}
}
</script>
Watch with old value
<script>
watch: {
count(newVal, oldVal) {
console.log(`Changed from ${oldVal} to ${newVal}`)
}
}
</script>
One-time watcher
<script>
watch: {
'$route'(to, from) {
this.fetchData(to.params.id)
}
}
</script>
Cleanup with onCleanup
<script>
setup() {
watch(userId, async (newId, oldId, onCleanup) => {
const controller = new AbortController()
onCleanup(() => controller.abort())
const data = await fetchUser(newId, {
signal: controller.signal
})
})
}
</script>
Mini Practice
- Create a basic watcher
- Use immediate and deep options
- Watch route changes
- Handle async in watchers
Up Next
Continue with Components - Building reusable UI.
Related Topics
Frequently Asked Questions about watch()
What is watch() in Vue?
watch() is a fundamental concept in Vue. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn watch()?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn watch().
Why is watch() important in Vue?
watch() is essential for Vue development. Understanding this concept will help you write better code and solve real-world problems more effectively.