Search code examples
vue.jsnuxt.jsvuejs3nuxt3.js

vue 3 watch specific object's item from array


I am working on nuxt 3 (vue 3) and I need to watch the particular item of the specific object from the array.

My array

const formData = reactive({
   addressDetails: [
     {
      address: "",
      street: "",
      suburb: "",
      state: "",
      postCode: "",
      country: "",
      unitNumber: "",
      streetNumber: "",
      streetName: "",
      timeAtaddressYears: "",
      timeAtaddressMonths: "0",
    },
     {
      address: "",
      street: "",
      suburb: "",
      state: "",
      postCode: "",
      country: "",
      unitNumber: "",
      streetNumber: "",
      streetName: "",
      timeAtaddressYears: "",
      timeAtaddressMonths: "0",
    },
   {
      address: "",
      street: "",
      suburb: "",
      state: "",
      postCode: "",
      country: "",
      unitNumber: "",
      streetNumber: "",
      streetName: "",
      timeAtaddressYears: "",
      timeAtaddressMonths: "0",
    },

   ]      
});

Here, I want to watch if any timeAtaddressYears items value has changed but not on the whole formData.addressDetails value. Ex if I add new address details then no need to any watch but in specific address details if I change any address's timeAtaddressYears then watch should be called.


Solution

  • I have found a similar one, we need to add a deep watcher if we want to watch the particular item of the specific object from the array.

    VueJS Deepwatchers

    watch(
      () => formData,
      (newValue, oldValue) => {
        console.log(newValue, oldValue);
      },
      { deep: true });