admin管理员组

文章数量:1391934

Sorry if its a very easy question, i tried following some answers in here but i couldnt..

I want to add a NEW object to an array, based on the first one

The way i find that works is this one:

    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
        }
    }
});

/

I understand that by using the mented array.push, i would just be adding the same reference to the object over and over, so when i change the value of failedExample.name, it will change in all positions of the array. Is there a way that this doesnt happens? Like, i add the first object, then the next one as a NEW instead of a reference?

Sorry if its a very easy question, i tried following some answers in here but i couldnt..

I want to add a NEW object to an array, based on the first one

The way i find that works is this one:

    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/myrgato/6mvx0y1a/

I understand that by using the mented array.push, i would just be adding the same reference to the object over and over, so when i change the value of failedExample.name, it will change in all positions of the array. Is there a way that this doesnt happens? Like, i add the first object, then the next one as a NEW instead of a reference?

Share Improve this question asked Jul 20, 2017 at 15:03 Vinicius SouzaVinicius Souza 1433 silver badges11 bronze badges 1
  • Can you give us an example of your desired oute? – larz Commented Jul 20, 2017 at 15:11
Add a ment  | 

1 Answer 1

Reset to default 6

It should work as you wanted to do with your 'failedExample'. The only wrong thing I see is that you forget the this keyword when you're pushing into array.

So try this one:

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

Update: If you want to add a new object each time, then try to clone it so you will not have refference problems:

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

本文标签: vuejs2How should i go when adding an object to an array using javascript and vueStack Overflow