Is there a way to watch a specific property of an object in vue 3?

Viewed 848

Here the doc only shows a way to watch the entire reactive object using

const state = reactive({ 
  id: 1, 
  name: "",
});

watch(
  () => state,
  (state, prevState) => { // ...
  }
);

what if I only want to watch the change of the name?

watch(state.name, (name, prevName) => {
    // for example: send a request to serve side for occupation validation
});

The code above is wrong.

2 Answers

You can watch the change of a single attribute like so:

const state = reactive({
  id: 1,
  name: ""
});

watch(
  () => state.name,
  (newName, prevName) => {
    /* ... */
  }
);
watch: {
    'state.name': function () {
         // updated...
    }
}

Hopefully it would be worked on your side.

Related