在 Vue.js 中,当你需要更新父组件通过 v-model
绑定的对象中的嵌套属性时,必须确保生成一个全新的对象以触发响应式更新。以下是修正后的代码和步骤说明:
// 在子组件中更新 freightFees[0].a
this.$emit('input', {
...this.value,
freightFees: [
{ ...this.value.freightFees[0], a: newVal },
...this.value.freightFees.slice(1)
]
});
...this.value
复制父组件传递的整个对象,保留其他属性不变。a
属性:{ ...this.value.freightFees[0], a: newVal }
。slice(1)
保留剩余元素,确保原数组不被直接修改。this.$emit('input', newValue)
发送,父组件的 v-model
会自动同步。.
或 []
,需通过重构数据的方式更新嵌套属性。map
或展开语法创建新数组,确保生成新引用。map
更优雅)const newFreightFees = this.value.freightFees.map((item, index) =>
index === 0 ? { ...item, a: newVal } : item
);
this.$emit('input', {
...this.value,
freightFees: newFreightFees
});
这种方法更灵活,适用于动态索引或复杂条件,保持代码可维护性。