생활
vuex의 mutations에서 state를 사용하지 않고 변경해도 될까요?
안녕하세요.
vuex에서 mutation 사용 시 궁금증이 있어서 글 남깁니다.
보통 store를 사용 시 state의 값은 반드시 mutation을 이용해서 값을 변경해야 됩니다.
근데 state에 itemArr이라는 배열이 존재하고 itemArr은 아래와 같습니다.
const itemArr = [ { id: 1, name: '상품A' options: ['옵션A', '옵션B'] }, { id: 2, name: '상품B', options: ['옵션C', '옵션D'] } ]itemArr 배열의 상품B의 옵션 중 옵션D를 삭제해야 되는 경우입니다.
지금까진 mutation의 첫번째 인자인 state에서 itemArr을 가져와서 상품을 찾고 다시 옵션을 찾은 후 삭제를 했습니다.
DELETE_ITEM(state, {itemId, optionName}) { const item = state.itemArr.find(item => item.id === itemId); const delIdx = item.options.findIndex(op => op === optionName); item.options.splice(delIdx, 1); }근데 mutation의 state에서 itemArr을 꺼내지 않고 바로 mutation에서 삭제대상이 되는 item 객체를 받아서 옵션을 삭제를 해도 되는지 궁금합니다.
DELETE_ITEM(_state, { item, optionName }) { // state는 안쓰임 delIdx = item.options.findIndex(op => op === optionName); item.options.splice(delIdx, 1); }vue의 컴포넌트의 메서드에서 commit할때 이미 대상이 되는 item 객체를 알고 있는데 mutation에서 다시 한번 state에서 itemArr을 꺼내서 item 객체를 찾는게 비효율적인거 같아서요
답변 부탁드립니다.
2개의 답변이 있어요!