Counter: {{ counter }}
Kilometers :
Meters :
const app ={
data(){
return{
kilometers :0,
meters:0
}
},
watch :{
kilometers:function(newValue, oldValue){
// Check if it's the current input field
if(this.currentlyActiveField==='kilometers'){
this.meters= newValue *1000
}
},
meters :function(newValue, oldValue){
// Check if it's the current input field
if(this.currentlyActiveField==='meters'){
this.kilometers= newValue/1000;
}
}
}
}
vm = Vue.createApp(app).mount('#app')
vm.$watch('kilometers',function(newValue, oldValue){
// This callback will be called after vm.kilometers changes
document.getElementById("info").innerHTML="Value before modification: "+ oldValue +"οΌValue after modification: "+ newValue;
})
[Try it Β»](#)
Click the "Try it" button to view the online example
In the above code, we created two input boxes. In the data property, both kilometers and meters have an initial value of 0. The watch object creates two monitoring methods for the data object: kilometers and meters.
When we enter data in the input boxes, watch will listen for data changes in real-time and change its own value. You can see the video demonstration below:
(#)
### Using watch in async loading
Vue provides a more general method through the watch option to respond to data changes when loading asynchronous data.
In the following example, we use the axios library, which will be explained in detail later.
## Example
const watchExampleVM = Vue.createApp({
data(){
return{
question:'',
answer:'A question mark (?) is required at the end of every question.'
}
},
watch:{
// This function runs whenever the question changes, ending with ?, supporting both English and Chinese ?
question(newQuestion, oldQuestion){
if(newQuestion.indexOf('?')>-1|| newQuestion.indexOf('οΌ')>-1){
this.getAnswer()
}
}
},
methods:{
getAnswer(){
this.answer='Loading...'
axios
.get('/try/ajax/json_vuetest.php')
.then(response =>{
this.answer= response.data.answer
})
.catch(error =>{
this.answer='Error! Cannot access API. '+ error
})
}
}
}).mount('#watch-example')
[Try it Β»](#)
* * *
## Usage Summary
watch is a reactive data monitoring mechanism provided by Vue 3, which can monitor single or multiple properties.
You can handle data changes by passing callback functions, supporting options like deep watching and immediate execution.
### 1. Basic Usage
In Vue 3, the watch function is used to monitor reactive properties.
When the monitored property value changes, Vue will trigger the callback function to execute.
## Example
import{ reactive, watch } from 'vue';
export default{
setup(){
const state = reactive({
count:0
});
watch(
()=> state.count,// The property to monitor
(newVal, oldVal)=>{// Callback function when changed
console.log(`count changed from ${oldVal} to ${newVal}`);
}
);
return{
state
};
}
};
### 2. Monitoring Multiple Reactive Properties
If you want to monitor multiple reactive properties at the same time, you can pass an array of properties to monitor:
## Example
import{ reactive, watch } from 'vue';
export default{
setup(){
const state = reactive({
count:0,
name:'Vue3'
});
watch(
[()=> state.count,()=> state.name],// Monitor multiple properties
([newCount, newName],[oldCount, oldName])=>{
console.log(`count changed from ${oldCount} to ${newCount}`);
console.log(`name changed from ${oldName} to ${newName}`);
}
);
return{
state
};
}
};
### 3. Deep Watching
If you need to monitor an object or array and want to listen to nested properties inside it, you can use the deep: true option. This will monitor all property changes of the object.
## Example
import{ reactive, watch }
YouTip