vue 3 从数组中观察特定对象的项目

问题描述 投票:0回答:3

我正在开发 nuxt 3 (vue 3),我需要从数组中观察特定对象的特定项目。

我的阵列

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",
    },

   ]      
});

在这里,我想观察是否有任何

timeAtaddressYears
项目值发生了变化,但整个
formData.addressDetails
值没有变化。例如,如果我添加新的地址详细信息,则无需任何手表,但在特定地址详细信息中,如果我更改任何地址的
timeAtaddressYears
,则应调用手表。

vue.js nuxt.js vuejs3 nuxtjs3
3个回答
2
投票
const formData = reactive({
   addressDetails: [
     {
      address: "",
      street: "",
      suburb: "",
      state: "",
      postCode: "",
      country: "",
      unitNumber: "",
      streetNumber: "",
      streetName: "",
      timeAtaddressYears: "",
      timeAtaddressMonths: "0",
    },
   ]      
})

const selected = computed(() => {
  return formData.addressDetails.map(form => form.timeAtaddressYears)
})

watch(selected, (newValue, oldValue) => {
      console.log(newValue, oldValue)
})

0
投票

你可以试试这个:

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

});

0
投票

我发现了一个类似的,如果我们想从数组中观察特定对象的特定项目,我们需要添加一个深度观察者

VueJS 深度观察者

watch(
  () => formData,
  (newValue, oldValue) => {
    console.log(newValue, oldValue);
  },
  { deep: true });
© www.soinside.com 2019 - 2024. All rights reserved.