【问题标题】:Unexpected behaviour when modify an array with Vue使用 Vue 修改数组时出现意外行为
【发布时间】:2019-10-08 07:08:28
【问题描述】:

我想保存一个原始数组并使用表单(在子 vue 组件中)修改副本。但是当副本被修改时,原点也被修改了。

我试过了:

this.updatedDatas = [...this.initialList]
this.updatedDatas = this.initialList.map((x)=> x)
this.updatedDatas = Array.from(this.initialList)

父脚本:

this.initialList = [{name: 'John'}, {name: 'Isa'}]
this.updatedDatas = [...this.initialList]

父模板:

<form-child :item="updatedDatas[1]" />

子模板:

<textarea v-model="item.name"></textarea>

子脚本:

this.$emit('updated', this.item)

【问题讨论】:

  • 我仍然遇到嵌套对象的问题。还有其他解决方案吗?

标签: javascript vue.js


【解决方案1】:

你需要对你的数组做一个深拷贝,否则你只会得到两个数组,它们具有相同的对象引用。深拷贝将重新创建对象和数组的内部结构。

您可以使用包线 lodash 或构建自己的。

外部库将为您提供“无限”深度,但这将为您提供 2 个级别,这对您来说可能就足够了。

this.updatedDatas = this.initialList.map(i => ({...i});

用于深度复制的其他资源

https://www.npmjs.com/package/clone

http://www.greywyvern.com/?post=363

【讨论】:

  • 也可以使用this.updatedData = JSON.parse(JSON.stringify(this.initialList))
  • 是的,虽然我不喜欢推荐JSON.stringify,因为它可能会导致像Uncaught TypeError: Converting circular structure to JSON 这样的错误。 clone 库往往能更好地处理这个问题。
猜你喜欢
  • 2014-05-21
  • 1970-01-01
  • 2016-05-24
  • 2021-09-28
  • 2011-05-08
  • 1970-01-01
  • 2018-06-22
  • 2020-10-14
  • 2020-12-31
相关资源
最近更新 更多