如何在不修改 vue 3 中的道具的情况下使用道具初始化状​​态

how to initialize state with props without modifying props in vue 3

我在我的 vue 3 组件中初始化状态如下:

data() {
    return {
        new_listing: this.listing //which is a prop
    }
}

然而,当我将它绑定到输入时:

<input type="text" placeholder="title" v-model="new_listing.title" />

预期的结果只有 new_listing.title 会改变,但是道具 listing 似乎也会改变。我该如何做到只有状态 new_listing.title 发生变化而不是道具 listing.title.

您需要克隆该对象(制作一个新副本)。

在 javascript 中,当将对象分配给变量时,它不会创建该对象的新副本。相反,它通过引用原始对象来分配它。

因此,根据您问题中的代码,执行 { new_listing: this.listing } 会将 this.listing 对象的引用分配给 new_listing。这意味着修改 new_listing 也会修改 this.listing:

要在 ES6+ 中克隆对象 ,您可以执行以下操作。 ...spread syntax。在这种情况下,它是一种克隆对象的方法。

data() {
    return {
        new_listing: {...this.listing} //which is a prop
    }
}

如果您不使用 ES6,请查看What is the most efficient way to deep clone an object in JavaScript? 了解如何克隆对象。

注意:如果对象包含对象(例如{a: {b: "h"}},那么您将需要执行a deep clone(在对象中克隆对象)。