IT이야기

Vuex를 사용하여 어레이의 개체를 업데이트하는 중

cyworld 2022. 3. 28. 21:11
반응형

Vuex를 사용하여 어레이의 개체를 업데이트하는 중

어레이 내의 개체를 Vuex로 업데이트하는 방법나도 해봤지만 소용이 없었어

const state = {
  categories: []
};

// mutations:
[mutationType.UPDATE_CATEGORY] (state, id, category) {
  const record = state.categories.find(element => element.id === id);
  state.categories[record] = category;
}

// actions:
updateCategory({commit}, id, category) {
  categoriesApi.updateCategory(id, category).then((response) => {
    commit(mutationType.UPDATE_CATEGORY, id, response);
    router.push({name: 'categories'});
  })
}
[mutationType.UPDATE_CATEGORY] (state, id, category) {
  state.categories = [
     ...state.categories.filter(element => element.id !== id),
     category
  ]
}

이것은 일치하는 요소 없이 '카테고리' 배열을 원래 배열로 교체한 다음 업데이트된 요소를 배열 끝에 연결함으로써 작동한다.

이 방법에 대한 한 가지 주의할 점은 많은 경우 문제가 되지 않겠지만 배열 순서를 파괴한다는 것이다.그냥 명심해야 할 것.

참조URL: https://stackoverflow.com/questions/50422357/updating-object-in-array-with-vuex

반응형