programing

javascript와 vue를 사용하여 객체를 어레이에 추가할 때 어떻게 해야 하는가?

prostudy 2022. 4. 18. 21:16
반응형

javascript와 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/

나는 코멘트 배열을 사용함으로써 그것을 이해한다.push, I would just adding the object에 동일한 참조를 반복해서 추가하기 때문에, failedExample.name의 값을 변경하면, 어레이의 모든 위치에서 변경될 것이다.이런 일이 일어나지 않을 방법이 있을까?예를 들어, 첫 번째 개체를 추가하고 다음 개체를 참조 대신 새 개체로 추가하시겠습니까?

'실패한 예시'를 원하는 대로 작동해야 한다.내가 잘못 본 것은 배열로 밀어넣을 때 이 키워드를 잊어버리는 것뿐입니다.

그러니 이걸 한번 시도해봐:

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

참조URL: https://stackoverflow.com/questions/45218555/how-should-i-go-when-adding-an-object-to-an-array-using-javascript-and-vue

반응형