programing

Vuex에서 서로 변환하지 않고 동일한 개체를 두 변수로 복사하려면 어떻게 해야 합니까?

prostudy 2022. 7. 8. 21:54
반응형

Vuex에서 서로 변환하지 않고 동일한 개체를 두 변수로 복사하려면 어떻게 해야 합니까?

제가 하려고 하는 것은 분산 연산자를 사용하여 오브젝트를 2개의 상태로 복사하는 것입니다만, 그 중 하나를 변경하면 다른 한쪽도 변경됩니다.

실제로 이 itemDetails에 대해 편집 작업을 구현하고 있습니다.이 작업은 마운트 시 가져오며 어레이 내에 여러 항목이 있습니다.편집 항목해당 항목에 대한 편집 모달이 열려 있을 때 인덱스가 전달됩니다.편집 항목을 교체한 후.

oItemDetails로 리셋하기 위해 itemDetails 복제를 복사하려고 하는데 oItemDetails 항목도 편집 후 변경됩니다.

참고문헌으로 복사를 피할 수 있는 몇 가지 제안을 해 주십시오.

state: {
    itemDetails: [],
    oItemDetails: [],
    editItem: [],
    editItemIndex: null,
},
actions: {
    async showItemsEditModal ({state, commit}, value) {
      commit('setItemsModalStatus', true);
      state.oItemDetails = await {...value};
      state.itemDetails = await {...value};
    },
    async openEditItemModal ({state, commit}, data) {
      state.editItem = await {...data.data}
      state.editItemIndex = await data.item_index
   },
   async editItem ({state, commit}, data) {
      state.itemDetails.items[state.editItemIndex] = await data
   },
   async resetItem ({state}) {
      console.log(state.itemDetails, state.oItemDetails)
      state.itemDetails = await {...state.oItemDetails}
   }
}

딥 객체의 복사 참조를 피하기 위해 딥 클론이 필요합니다.lodash clone deep또는JSON.parse(JSON.stringify(value))대신{...value}.

퍼포먼스는JSON.parse그리고.JSON.stringify좋지 않습니다. lodash clone deep이 더 나은 솔루션입니다.

개체를 복제하여 변수에 저장하고 클론을 사용하려면 클론을 복제하고 전달하는 대신 산포를 인수로 전달합니다.

클로닝의 일반적인 예를 다음에 나타냅니다.

원래 개체가 업데이트된 후에도 복제본이 변경되지 않습니다.

const exampleObject = {
  title: "Crystal Silence",
  artist: "Chick Corea"
}

// Clone the object

const clone = {...exampleObject};

// NOTE: JSON.stringify is used for display purposes only

let display = "";
display = "Example Object before: " + JSON.stringify(exampleObject) +  "<br/>";
display += "Clone before: " + JSON.stringify(clone) +  "<br/>";

// Now change the exampleObject by adding a new attribute

exampleObject.album = "Return to Forever";

// And check what happens to the clone:

display += "Example Object after: " + JSON.stringify(exampleObject) + "<br/>" ;
display += "Clone after: " + JSON.stringify(clone);

const main = document.getElementById("main");
main.innerHTML = display;
<div id="main"></div>

언급URL : https://stackoverflow.com/questions/58618890/how-to-copy-same-object-to-two-variable-without-mutating-each-other-in-vuex

반응형