简体   繁体   English

如何初始化数据但不改变原始数据

[英]How to initialize data but make it not to change original

There is need to initalize Vue data "settings" from other object "original_settings" but not to change this object when data "settings" is changed.需要从其他对象“original_settings”初始化 Vue 数据“设置”,但在数据“设置”更改时不要更改此对象。 How to make it happen?如何让它发生?

new Vue({
    el: "#app",
    data: {
        settings: original_settings        
    }
});

You can use JSON.parse(JSON.stringify(obj)) in order to create a deep clone copy of the object.您可以使用JSON.parse(JSON.stringify(obj))来创建对象的deep克隆副本。

new Vue({
   el: "#app",
   data: {
     settings: JSON.parse(JSON.stringify(original_settings))        
   }
});

Another solution is to use Object.assign from ES6 .另一种解决方案是使用ES6中的Object.assign

new Vue({
   el: "#app",
   data: {
     settings: Object.assign({}, original_settings)        
   }
});

I don't think this is the good solution.我不认为这是一个好的解决方案。 see documentation about data : https://v2.vuejs.org/v2/api/#data请参阅有关数据的文档: https ://v2.vuejs.org/v2/api/#data

documentation :文档:

it is not recommended to observe objects with their own stateful behavior.不建议观察具有自己状态行为的对象。 Once observed, you can no longer add reactive properties to the root data object一旦观察到,您就不能再将反应属性添加到根数据对象

If you need to bind data from external object, you can use computed properties to access them, or you can use a store (VueX).如果您需要绑定来自外部对象的数据,您可以使用计算属性来访问它们,或者您可以使用存储(VueX)。

you can do something like this :你可以这样做:

var original_settings = { foo: 'var'}

new Vue({
  el: '#el',
  data: {
    //empty
  },
  computed: {
    foo: {
      get: function () {
        return original_settings.foo
      },
      set: function (value) {
        original_setting.foo = value
      }
    }
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM