我正在尝试将数据从 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>
最佳答案
因为你在内存中编辑的对象都是同一个引用,比如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/