Home > Software engineering >  vue 3 watch individual state property
vue 3 watch individual state property

Time:10-23

My setup function:

  setup() {

    const state = reactive({
      // .....
      venueFilter: null,
    })


    const venueFilter = ref(state.venueFilter);
    watch(venueFilter, ()=> {
      console.log('invoked watch');
      if(venueFilter) {
        doSomething();
      }
    });

    return {
      ...toRefs(state),
      //.....
    }
  }

The watch above is not getting fired(console.log('invoked watch'); is not getting printed when state.venueFilter changes in the template. So how do I watch the state.venueFilter?

CodePudding user response:

You can't make a ref from a property of a reactive object like that. This line:

const venueFilter = ref(state.venueFilter); //venueFilter will not react to changes in state.venueFilter

Instead, you can pass in a getter function as the first argument to watch that returns a value:

watch(()=>state.venueFilter, ()=> {
  console.log('invoked watch');
});

Here's a working example to demonstrate

You also could have called toRefs(state) first and passed in the venueFilter ref created from that.

  • Related