Vue.js是否有内置的方法将持久对象的副本添加到重复的数组中

时间:2015-06-01 16:11:12

标签: javascript vue.js

我有一个Vue.js应用程序,我对一系列项目进行了v-repeat。我想将newItem添加到项目列表中。当我尝试this.items.push(this.newItem)时,推送的对象仍然绑定到输入。请考虑以下内容:

new Vue({
  el: '#demo',

  data: {
    items: [
      {
        start: '12:15',
        end: '13:15',
        name: 'Whatch Vue.js Laracast',
        description: 'Watched the Laracast series on Vue.js',
        tags: ['learning', 'Vue.js', 'Laracast', 'PHP'],
        note: "Vue.js is really awesome. Thanks Evan You!!!"
      },
      {
        start: '13:15',
        end: '13:30',
        name: "Rubik's Cube",
        description: "Play with my Rubik's Cube",
        tags: ['Logic', 'Puzzle', "Rubik's Cube"],
        note: "Learned a new algorithm."
      }
    ],
    newItem: {start: '', end: '', name: '', description: '', tags: '', note: ''}
  },

  methods: {
    addItem: function(e) {
      e.preventDefault();

      this.items.push(this.newItem);
    }
  }
});

正如预期的那样,上面将推送绑定到items数组的对象。问题是我只想要一个对象的副本,以便在输入更改时它不再更改。见this fiddle。我知道我能做到:

addItem: function(e) {
  e.preventDefault();
  this.items.push({
    name:        this.newItem.name,
    start:       this.newItem.start,
    end:         this.newItem.end,
    description: this.newItem.description,
    tags:        this.newItem.tags,
    notes:       this.newItem.notes
  })
}

This works但是重复很多。

问题:是否有内置方法只添加对象的副本而不是持久对象。

4 个答案:

答案 0 :(得分:37)

请参阅GitHub上的this issue。我正在使用jQuery的$.extend,直到Evan You指出有一个未记录的构建它的扩展函数Vue.util.extend,相当于jQuery的扩展,深度设置为true。所以你将使用的是:

addItem: function(e) {
  e.preventDefault();

  this.items.push(Vue.util.extend({}, this.newItem));
}

请参阅updated Fiddle

答案 1 :(得分:6)

这对我不起作用(vue 1.0.13)。我使用以下内容创建没有数据绑定的副本:

this.items.push( JSON.parse( JSON.stringify( newItem ) ) );

答案 2 :(得分:4)

您可以将Vanilla JavaScript与Object.assign()一起使用:

addItem: function(e) {
  e.preventDefault();

  this.items.push(Object.assign({}, this.newItem));
}

<强>更新

您也可以使用Object Spread:

addItem: function(e) {
  e.preventDefault();

  this.items.push({...this.newItem});
}

答案 3 :(得分:-1)

最高答案是错误的。 Vue.util.extend与jQuery的扩展无关。它总是一个浅表克隆。 https://github.com/vuejs/vue/issues/1849#issuecomment-158770874

Object.assign和Spread运算符也是浅表副本。看到这个https://scotch.io/bar-talk/copying-objects-in-javascript

仅使用Ramda.js的实现 https://github.com/ramda/ramda/blob/v0.26.1/source/internal/_clone.js

如果您不想要_curry,则不需要。

或检查此MVA What is the most efficient way to deep clone an object in JavaScript?