Search code examples
typescriptvue.jsvuejs3

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


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.


Solution

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

    const state = reactive({
      id: 1,
      name: ""
    });
    
    watch(
      () => state.name,
      (newName, prevName) => {
        /* ... */
      }
    );