Does Vue.js have a built in way to add a copy of a persistent object to a repeated array

后端 未结 4 1417
逝去的感伤
逝去的感伤 2020-12-03 07:28

I have a Vue.js app where I have a v-repeat on an array of items. I want to add a newItem to the list of items. When I try this.items.push(this.newItem) the obj

相关标签:
4条回答
  • 2020-12-03 07:44

    The top answer is wrong. Vue.util.extend has nothing to do with jQuery's extend. It's always a shallow clone. https://github.com/vuejs/vue/issues/1849#issuecomment-158770874

    Object.assign and Spread operator are also shallow copy. see this https://scotch.io/bar-talk/copying-objects-in-javascript

    Simply use the implementation of Ramda.js https://github.com/ramda/ramda/blob/v0.26.1/source/internal/_clone.js

    _curry is not necessary if you don't want them.

    Or check this MVA What is the most efficient way to deep clone an object in JavaScript?

    0 讨论(0)
  • 2020-12-03 07:46

    This didn't work for me (vue 1.0.13). I used the following to create a copy without the data bindings:

    this.items.push( JSON.parse( JSON.stringify( newItem ) ) );
    
    0 讨论(0)
  • 2020-12-03 07:55

    You can use Vanilla JavaScript with Object.assign():

    addItem: function(e) {
      e.preventDefault();
    
      this.items.push(Object.assign({}, this.newItem));
    }
    

    UPDATE:

    You can also use Object Spread:

    addItem: function(e) {
      e.preventDefault();
    
      this.items.push({...this.newItem});
    }
    
    0 讨论(0)
  • 2020-12-03 07:56

    See this issue on GitHub.

    Shallow Clone

    I was using jQuery's $.extend until Evan You pointed out there is an undocumented built it extend function Vue.util.extend that does a shallow clone. So what you could use is:

    addItem: function(e) {
      e.preventDefault();
    
      this.items.push(Vue.util.extend({}, this.newItem));
    }
    

    See the updated Fiddle.

    Deep Clone

    When doing a shallow clone on an object that references other objects you copy the references to the external objects instead of cloning them. To clone the object completely do a Deep Clone.

    For the deep clone, per Evan's suggestion in the first link, one could use: JSON.parse(JSON.stringify(object)). This can be seen between this fiddle and this fiddle.

    If using lodash check out lodash cloneDeep. If using NPM check out clone-deep.

    0 讨论(0)
提交回复
热议问题