How to Use watch in Vue: Simple Guide with Examples
In Vue, use the
watch option or the watch function inside the setup() to react to changes in reactive data or props. It lets you run code whenever a specific value changes, useful for side effects or asynchronous tasks.Syntax
The watch function in Vue observes a reactive source and runs a callback when the source changes.
- source: The reactive data or getter function to watch.
- callback: Function called with new and old values.
- options: Optional settings like immediate or deep watching.
javascript
watch(source, (newValue, oldValue) => {
// code to run when source changes
}, { immediate: false, deep: false })Example
This example shows a Vue component that watches a count variable and logs changes. It also updates a message when count changes.
vue
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="count++">Increment</button>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref, watch } from 'vue'
const count = ref(0)
const message = ref('')
watch(count, (newVal, oldVal) => {
console.log(`Count changed from ${oldVal} to ${newVal}`)
message.value = `Count is now ${newVal}`
})
</script>Output
Count: 0
[Button: Increment]
When clicking Increment:
Console logs: Count changed from 0 to 1
Message updates to: Count is now 1
Common Pitfalls
Common mistakes when using watch include:
- Not using a function or ref as the source, causing no reaction.
- Forgetting to handle deep changes in objects or arrays.
- Expecting immediate callback without setting
immediate: true.
Example of wrong and right usage:
javascript
// Wrong: watching a plain object directly const obj = { a: 1 } watch(obj, () => { console.log('Won\'t run') }) // Right: watch a reactive object or use a getter import { reactive, watch } from 'vue' const obj = reactive({ a: 1 }) watch(() => obj.a, (newVal) => { console.log('Value changed to', newVal) })
Quick Reference
Tips for using watch in Vue:
- Use
watchinsidesetup()for Composition API. - Use
immediate: trueto run callback on initial setup. - Use
deep: trueto watch nested object changes. - Use a getter function to watch computed or specific parts of reactive data.
Key Takeaways
Use
watch to react to changes in reactive data or computed values in Vue.Pass a reactive source and a callback to
watch inside setup() for Composition API.Set
immediate: true to run the watcher callback right away on setup.Use
deep: true to watch nested changes in objects or arrays.Always watch reactive refs, reactive objects, or getter functions, not plain objects.