VueJs如何从v-repeat复制对象?

时间:2015-09-22 22:15:38

标签: javascript arrays object mvvm vue.js

功能允许您添加/删除事件的描述,标题和时间。

我无法处理通过v-model =(event.name,event.description和event.date)创建的对象的复制(克隆)

一切正常,删除所选对象,它的工作方式如下:

deleteEvent: function(index){
  if(confirm('Are you sure?')) {
    this.events.$remove(index);
  }
}

以下是我添加和更改事件的应用程序代码的示例。

 var vm = new Vue({
  el: '#events',

  data:{
    event: { name:'', description:'', date:'' },
    events: []
  },

  ready: function(){
     this.fetchEvents();
  },

  methods: {
     fetchEvents: function() {
      var events = [
        {
          id: 1,
          name: 'TIFF',
          description: 'Toronto International Film Festival',
          date: '2015-09-10'
        },
        {
          id: 2,
          name: 'The Martian Premiere',
          description: 'The Martian comes to theatres.',
          date: '2015-10-02'
        },
        {
          id: 3,
          name: 'SXSW',
          description: 'Music, film and interactive festival in Austin, TX.',
          date: '2016-03-11'
        }
      ];

      this.$set('events', events);
    },

    addEvent: function() {
      if(this.event.name) {
        this.events.push(this.event);
        this.event = { name: '', description: '', date: '' };
      }
    },

  deleteEvent($index)"
    deleteEvent: function(index){
      if(confirm('Вы точно хотите удалить данную запись?')) {
        this.events.$%remove(index);
      }
    },
    cloneItem: function(index) {

    }

  }
});

有完整的代码 http://codepen.io/Monocle/pen/ojLYGx

2 个答案:

答案 0 :(得分:1)

我发现未记录的构建它的扩展函数Vue.util.extend等同于jQuery的扩展。

在这种情况下,您可以避免枚举对象属性

cloneItem: function(index) {
  this.events.push(Vue.util.extend({},this.events[index]));
}

答案 1 :(得分:0)

通过this.events[index]访问克隆对象,然后使用它的属性创建新对象并将其推入events数组:

cloneItem: function(index) { 
    this.events.push({ name: this.events[index].name, 
                       description: this.events[index].description, 
                       date: this.events[index].date });      
}

演示:http://codepen.io/anon/pen/MajKZO