programing

Vuex 스토어 내 2차원 배열에서 항목 업데이트

prostudy 2022. 6. 10. 21:29
반응형

Vuex 스토어 내 2차원 배열에서 항목 업데이트

저는 VueJs 개발에 참여해서 간단한 지뢰찾기 게임을 만들고 싶습니다.2차원 그리드는 Vuex 상태에 의해 관리됩니다.셀을 클릭할 때 현재 코드를 표시하려고 합니다.

  [MutationTypes.REVEAL_CELL]: (state, { rowIndex, columnIndex }) => {
    state.board[rowIndex][columnIndex].isRevealed = true;
  }

유감스럽게도 UI에는 영향을 주지 않습니다.이 문제는 여기서 설명하고 있습니다.

https://vuejs.org/v2/guide/list.html#Caveats

의사 선생님들이 이런 걸 쓰라고 해서

import Vue from "vue";

  [MutationTypes.REVEAL_CELL]: (state, { rowIndex, columnIndex }) => {
    const updatedCell = state.board[rowIndex][columnIndex];
    updatedCell.isRevealed = true;

    Vue.set(state.board[rowIndex], columnIndex, updatedCell);
    Vue.set(state.board, rowIndex, state.board[rowIndex]);
  }

하지만 도움이 되지 않았다.마지막으로 보드의 복사본을 만들고 값을 수정하여 보드에 할당하려고 했습니다.

  [MutationTypes.REVEAL_CELL]: (state, { rowIndex, columnIndex }) => {
    const newBoard = state.board.map((row, mapRowIndex) => {
      return row.map((cell, cellIndex) => {
        if (mapRowIndex === rowIndex && cellIndex === columnIndex) {
          cell = { ...cell, isRevealed: true };
        }
        return cell;
      });
    });

    state.board = newBoard;
  }

이것도 효과가 없었어요.누구 아이디어 있어?

나는 내 프로젝트를 보여주는 Codesandbox를 만들었다.

https://codesandbox.io/s/vuetify-vuex-and-vuerouter-d4q2b

하지만 관련된 파일은 /store/gameBoard/mutations.jsDECHLOW_CELL 함수뿐이라고 생각합니다.

문제는 에 있습니다.Cell.vue문제는 불변 변수를 체크해서 폭로 상태를 확인하는 거예요추상화되었습니다.this.cell.isRevealed라고 하는 변수로isUnrevealed초기 로드 후 변경 방법을 알 수 없습니다.

옵션 1

isUnrevealed불필요한 편의 변수로 보입니다.없애버리면isUnrevealed참조처를 변경해 주세요.!cell.isRevealed코드는 예상대로 동작합니다.

옵션 2

이 변수를 사용하도록 설정한 경우 Vuex 상태가 에 변경을 전파할 때마다 자동으로 업데이트되도록 이 변수를 계산으로 변경하십시오.cell isRevealed소품:

computed: {
  isUnrevealed() {
    return !this.cell.isRevealed;
  }
}

이 경로로 갈 경우, 잊지 말고 다음 경로에서data에서 할당을 삭제합니다.mounted(첫줄).


또, 같은 문제가 발생하게 됩니다.isMine그리고.cellStyle완전히 제거해 주세요.data그리고.mounted둘 다 계산하게 만들어요.

computed: {
  isMine() {
    return this.cell.isMine;
  },
  cellStyle() {
    if (!this.cell.isRevealed) {
      return "unrevealedCell";
    } else {
      if (this.isMine) {
        return "mineCell";
      } else {
        let neighbourCountStyle = "";
        ... // Switch statement
        return `neutralCell ${neighbourCountStyle}`;
      }
    }
  }
}

언급URL : https://stackoverflow.com/questions/56516335/update-item-in-two-dimensional-array-within-the-vuex-store

반응형