为什么 prop 值随着 vuejs3 中数据的变化而变化?

why prop value is changing with data changes in vuejs3?

我得到的道具

props : {
     images : Object,
     locale : String,
},

数据方法

data() {
        return {
            form : this.$inertia.form({
                product_images : this.images.data,
            }),
        }
    },

我正在更新 project_images 点击事件

Add() {
       this.form.product_images.push({image : null});
},

但这里的问题是 project_images 使用新对象更新。它还会更新道具图像(在图像道具的数据字段中添加对象,如 product_images)。我不希望更改该道具,因为我使用的是旧道具值。为什么会发生这种奇怪的事情?

JavaScript 数组是通过引用复制的,因此 form.product_imagesimages.data 指的是内存中的同一个数组。编辑一个变量会影响另一个变量。

解决方法是将原数组深拷贝到新数组中。一种方法是 map the array into newly spread objects:

data() {
  return {
    form : this.$inertia.form({
      product_images : this.images.data.map(x => ({...x})),
    }),
  }
},