YouTip LogoYouTip

Vue3 Watch

In this chapter, we will introduce Vue3's **watch** property, which allows us to respond to data changes. **watch** is used to monitor changes to reactive properties and execute specific operations when properties change. It is a reactive mechanism in Vue that allows you to respond to data changes and execute custom logic. **watch** provides more control and flexibility when reactive properties change, allowing your components to better respond to data changes and execute corresponding logic. The following example implements a counter using watch: ## Example

Counter: {{ counter }}

const app ={ data(){ return{ counter:1 } } } vm = Vue.createApp(app).mount('#app') vm.$watch('counter',function(nval, oval){ alert('Counter value changed: '+ oval +' to '+ nval +'!'); }); [Try it Β»](#) The following example converts between **kilometers** and **meters**: ## Example
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 }
← Vue3 EventsVue3 Components β†’