search

Home  >  Q&A  >  body text

Observe changes to nested properties in Vue 3

I created a simple state management with a reactive API

My store file looks like this:

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'm trying to observe changes in state.form.service_id but I get the following error:

[Vue warn]: Invalid watch source: state.form.service_id Watch sources can only be getter/effect functions, refs, reaction objects, or arrays of these types

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

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

But I need to pay attention to the changes in state.form.service_id. Is there any solution?

P粉060112396P粉060112396263 days ago437

reply all(1)I'll reply

  • P粉129275658

    P粉1292756582024-04-01 13:14:13

    Try using getter functions instead of property paths:

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

    reply
    0
  • Cancelreply