Home > Enterprise >  Watch change in nested property in Vue 3
Watch change in nested property in Vue 3

Time:02-12

I have created a Simple State Management with Reactivity API

My Store file looks like the following:

import { reactive, watch  } from "vue";

const state = reactive({
   form : {
    service_id : null
   }
})

 watch('state.form.service_id', (newVal, oldVal) => {
     console.log('service changed');
 }, { deep: true });
 

export default {
  state, 
}

I am trying to watch the change in state.form.service_id, but I am getting the following error:

[Vue warn]: Invalid watch source: state.form.service_id A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types

If I replace the watch code with the following, then it works.

 watch('state.form', (newVal, oldVal) => {
     console.log('form changed');
 }, { deep: true });

But I need to watch for the change in state.form.service_id. Is there any solution?

CodePudding user response:

Try to use a getter function instead of the property path :

 watch(()=>state.form.service_id, (newVal, oldVal) => {
     console.log('service changed');
 }, { deep: true });
 

  • Related