Vue中调用splice删除一个数组元素后另一个同源数组也被修改是什么原因
问题原因
数组是JS中的引用类型,你在initData中直接将同一个response赋值给arrayA和arrayB时,两个变量实际指向内存中的同一份数组对象,无论操作哪一个变量修改数组内容,本质都是修改同一份数据,因此两个数组会同步变动。
解决方案
赋值时对数组做拷贝生成独立的新数组即可,根据业务场景可选择浅拷贝或深拷贝:
- 若数组元素为基础类型,或后续无需修改数组内的对象属性,使用浅拷贝即可,修改
initData的赋值逻辑:
async initData() { const { data: response } = await this.$store.dispatch("getData", { id: this.$route.params.id }) // 浅拷贝方式1:展开运算符 this.arrayA = [...response] this.arrayB = [...response] // 浅拷贝方式2:Array.from (二选一即可) // this.arrayA = Array.from(response) // this.arrayB = Array.from(response) }
- 若后续需要修改数组内的对象属性,且要求两个数组的改动互不影响,使用深拷贝:
async initData() { const { data: response } = await this.$store.dispatch("getData", { id: this.$route.params.id }) // 普通场景可直接用JSON序列化反序列化实现深拷贝 this.arrayA = JSON.parse(JSON.stringify(response)) this.arrayB = JSON.parse(JSON.stringify(response)) // 若有特殊类型(如函数、Symbol、BigInt等),可使用项目内置的深拷贝工具实现 }
内容的提问来源于stack exchange,提问作者Morgan Millet
相关产品推荐
相关产品推荐

