Observe changes to nested properties in Vue 3
P粉060112396
P粉060112396 2024-03-31 18:31:30
0
1
383

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粉060112396
P粉060112396

reply all(1)
P粉129275658

Try using getter functions instead of property paths:

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template