gpt4 book ai didi

javascript - VueJS 在不更改父数据的情况下编辑 Prop 的正确方法

转载 作者:可可西里 更新时间:2023-11-01 02:33:32 25 4
gpt4 key购买 nike

在我的父 vue 组件中,我有一个 user 对象。

如果我将该用户对象作为 prop 传递给子组件:

<child :user="user"></child>

在我的子组件中我更新了 user.name,它也会在父组件中更新。

我想编辑子组件中的用户对象,而更改不会反射(reflect)在父组件中的用户对象中。

有没有比克隆对象更好的方法:JSON.parse(JSON.stringify(obj))

最佳答案

您不必使用 JSON 对象。

const child = {
props:["user"],
data(){
return {
localUser: Object.assign({}, this.user)
}
}
}

在你的 child 中使用 localUser(或任何你想给它起的名字)。

编辑

我已经修改了为这个问题的另一个答案创建的 fiddle 以演示上述概念并询问了@user3743266

I'm coming to grips with this myself, and I'm finding this very useful. Your example works well. In the child, you've created an element in data that takes a copy of the prop, and the child works with the copy. Interesting and useful, but... it's not clear to me when the local copy gets updated if something else modifies the parent. I modified your fiddle, removing the v-ifs so everything is visible, and duplicating the edit component. If you modify name in one component, the other is orphaned and gets no changes?

当前组件如下所示:

Vue.component('edit-user', {
template: `
<div>
<input type="text" v-model="localUser.name">
<button @click="$emit('save', localUser)">Save</button>
<button @click="$emit('cancel')">Cancel</button>
</div>
`,
props: ['user'],
data() {
return {
localUser: Object.assign({}, this.user)
}
}
})

因为我决定使用用户的本地副本,@user3743266 是正确的,组件不会自动更新。 property user 已更新,但 localUser 未更新。在这种情况下,如果您希望在属性更改时自动更新本地数据,您将需要一个观察者。

Vue.component('edit-user', {
template: `
<div>
<input type="text" v-model="localUser.name">
<button @click="$emit('save', localUser)">Save</button>
<button @click="$emit('cancel')">Cancel</button>
</div>
`,
props: ['user'],
data() {
return {
localUser: Object.assign({}, this.user)
}
},
watch:{
user(newUser){
this.localUser = Object.assign({}, newUser)
}
}
})

这是更新的 fiddle .

这使您可以完全控制何时/是否更新或发出本地数据。例如,您可能希望在更新本地状态之前检查条件。

  watch:{
user(newUser){
if (condition)
this.localUser = Object.assign({}, newUser)
}
}

正如我在别处所说,有时您可能想要利用可变的对象属性,但也有像这样的时候您可能需要更多控制。

关于javascript - VueJS 在不更改父数据的情况下编辑 Prop 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44790842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com