使用 javascript 和 vue 将对象添加到数组时我应该怎么做?

How should i go when adding an object to an array using javascript and vue?

抱歉,如果这是一个非常简单的问题,我尝试按照此处的一些答案进行操作,但我做不到..

我想在第一个对象的基础上向数组添加一个新对象

我发现的方法是这个:

    new Vue({
    el: "#app",
    data: {
       name: '',  //name isnt inside and object
     //failedExample: {name: ''}
        array: []
    },
    methods: {
        add(){
            this.array.push({name: this.name}) // i push a key:value
          //this.array.push(failedExample) // what i wished to do
        }
    }
});

https://jsfiddle.net/myrgato/6mvx0y1a/

我知道通过使用注释 array.push,我只会一遍又一遍地添加对对象的相同引用,所以当我更改 failedExample.name 的值时,它会更改数组的所有位置。有没有办法不发生这种情况?比如,我添加第一个对象,然后将下一个作为新对象而不是引用添加?

它应该可以像您希望的那样使用您的 'failedExample'。唯一不对的地方 我看到你在推入数组时忘记了 this 关键字。

所以试试这个:

 new Vue({
    el: "#app",
    data: {
      failedExample: { name: 'test'},
      array: []
    },
    methods: {
        add(){
          this.array.push(this.failedExample);
          console.log(this.array);
        }
    }
});

更新:如果你每次都想添加一个新对象,那么尝试克隆它,这样你就不会出现引用问题:

this.array.push(Object.assign({}, this.failedExample));