简体   繁体   中英

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",
    },
   ]      
});

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.

You can try this:

watch(() => formData.addressDetails[0].address, (newValue, oldValue) => {

});
new Vue({
  el: '#app',
  data: () => ({
    forms: [{
        day: '12',
        month: '9',
        year: '2035',
        colors: 'lightblue',
        selected: true
      },
      {
        day: '28',
        month: '01',
        year: '2017',
        colors: 'lightgreen',
        selected: true
      }
    ],
  }),
  computed: {
    selected() {
      return this.forms.map(form => form.selected)
    }
  },
  watch: {
    selected(newValue) {
      console.log("change made to selection")
    }
  }
})

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.

https://vuejs.org/guide/essentials/watchers.html#deep-watchers

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM