javascript - Vue 复制对象到本地数据

标签 javascript vue.js

我正在尝试将数据从 prop 复制到本地 data() 值以进行编辑,但当我进行更改时它会继续编辑。

export default {
  props: {
    item: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      form: { ...this.item }
    }
  }
}

然后我将本地表单数据的 Translations 属性传递给另一个处理编辑的组件

<tab
   v-for="translation in form.translations"
   :key="translation.locale.value"
   :name="translation.locale.value">
   <form-group :fields="translation" />
</tab>

在我的 FormGroup 组件中,我接收到传递的字段,将它们过滤掉以使隐藏的字段不显示,然后编辑它们。

现在,当我编辑时,我在我的 Vue 检查器中看到我的父组件中的原始项目也正在被编辑。

<script>
export default {
  props: {
    fields: {
      type: Object,
      required: true
    }
  },
  computed: {
    filtered () {
      return Object.keys(this.fields)
        .filter(field => this.fields[field].type !== 'hidden')
        .reduce((res, field) => Object.assign(res, { [field]: this.fields[field] }), {})
    }
  }
}
</script>

enter image description here

enter image description here

最佳答案

因为你在内存中编辑的对象都是同一个引用,比如Array、Function和Object。

像这样,使用Object.assign():

let obj1 = { a: 0 , b: { c: 0}};
let obj2 = Object.assign({}, obj1);
console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}}

然后编辑obj2:

obj2.a = 33
console.log(obj1)  // { a: 0 , b: { c: 0}}

关于javascript - Vue 复制对象到本地数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55137269/

相关文章:

javascript - 无法过滤Vue js中的对象数组

vue.js - 如何将事件绑定(bind)到 Vuetify 中的 TreeView 节点?

php - 如果操作 == 某事,则提交表单

Javascript 'this' 作为参数

javascript - Expo/RN - 获取人脸特征点

javascript - Firebase 仅发送已过期的电子邮件验证链接

php - 当我上传新版本的代码时如何强制浏览器清除缓存

vue.js - 访问 Vue.js 中已删除的元素

javascript - 如何在下拉列表中选择完整的日历月份和年份

cookies - Vue-Cookies : this. $cookies 未定义