Vue中关于Object.assign(obj, this.currentRow )复制对象到底是不是真正的复制,Object.assign()复制仍指向原对象的问题

Vue中关于Object.assign(obj, this.currentRow )复制对象到底是不是真正的复制,那要看你的原对象currentRow 是否是响应式对象,
如果 this.currentRow 对象的属性是响应式的(例如 Vue.js 的响应式数据),那么 Object.assign() 会保留响应式特性。因此,对 obj 对象的修改可能会触发响应式更新,并在界面上更新 this.currentRow 对象的属性。

当然还有情况,对象的属性是引用类型:如果 this.currentRow 对象的某些属性是引用类型(如数组或对象),那么在使用 Object.assign() 复制属性时,复制的是引用而不是值。这意味着 obj 和 this.currentRow 仍然引用相同的引用类型对象。因此,修改 obj 中引用类型属性的值可能会反映在 this.currentRow 中
如果您想确保 Object.assign() 不会影响 this.currentRow 对象的属性,可以使用深拷贝来复制对象属性,确保生成一个新的对象。您可以使用 JSON.parse(JSON.stringify()) 进行深拷贝,或使用其他深拷贝的工具库来复制对象属性。

const obj = JSON.parse(JSON.stringify(this.currentRow));

这将创建一个新的对象 obj,其属性与 this.currentRow 相同,但是它们是完全独立的对象,修改 obj 不会影响 this.currentRow。

请注意,深拷贝有一些限制,例如无法复制函数、循环引用等。因此,根据实际情况选择适当的深拷贝方法。

猜你喜欢

转载自blog.csdn.net/Spy003/article/details/131727654
今日推荐