如何避免 vue 中的反应性

Ptt*_*lez 5 laravel vue.js

我正在将属性“模型”(我从 Laravel 中的刀片属性模型获得)中的对象分配给数据属性模型。后来数据属性模型更改,因为它绑定到表单输入字段。但是道具“模型”也会发生变化。它们是同一个对象。我怎样才能避免这种行为?我需要属性“模型”保持安装时的状态。我在 created() 方法和 data() 中尝试了这个:

 Vue.set(this, 'model', this.transferredData.model);
Run Code Online (Sandbox Code Playgroud)

那没有帮助

Pra*_*lan 6

您可以使用扩展语法来创建一个新对象,这样它只会改变新创建的对象。

Vue.set(this, 'model', {...this.transferredData.model});
// or Vue.set(this, 'model', Object.assign({}, this.transferredData.model)); 
Run Code Online (Sandbox Code Playgroud)

注意:如果它是嵌套的,那么您必须递归解构,或者您可以使用:

Vue.set(this, 'model',JSON.parse(JSON.stringify(this.transferredData.model)))
Run Code Online (Sandbox Code Playgroud)