【问题标题】:How should i go when adding an object to an array using javascript and vue?使用 javascript 和 vue 将对象添加到数组时我应该怎么做?
【发布时间】:2017-12-26 09:03:58
【问题描述】:

对不起,如果这是一个非常简单的问题,我尝试在此处遵循一些答案,但我不能..

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

我发现可行的方法是这样的:

    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 的值时,它会在数组的所有位置发生变化。有没有办法不发生这种情况?比如,我添加第一个对象,然后将下一个对象作为 NEW 而不是引用?

【问题讨论】:

  • 你能给我们举一个你想要的结果的例子吗?

标签: javascript vuejs2 v-model


【解决方案1】:

它应该像您对“失败示例”所做的那样工作。唯一的错误 我看到你在推入数组时忘记了 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));

【讨论】:

  • 完美!非常感谢!
猜你喜欢
  • 2012-05-20
  • 2017-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-27
  • 1970-01-01
  • 2021-06-21
  • 2021-03-30
相关资源
最近更新 更多