我正在开发 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
,则应调用手表。
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)
})
你可以试试这个:
watch(() => formData.addressDetails[0].address, (newValue, oldValue) => {
});
我发现了一个类似的,如果我们想从数组中观察特定对象的特定项目,我们需要添加一个深度观察者。
watch(
() => formData,
(newValue, oldValue) => {
console.log(newValue, oldValue);
},
{ deep: true });