更新 Vuex 商店中二维数组中的项目



我想进入 VueJs 开发并创建一个简单的扫雷游戏。二维网格由 Vuex 状态管理。单击单元格时,我想显示它,所以我当前的代码是

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

不幸的是,这对 UI 没有影响。此问题是已知并在此处描述

https://v2.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;
  }

这也行不通。有人有想法吗?

我创建了一个显示我的项目的代码沙盒

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

但我认为唯一相关的文件是/store/gameBoard/mutations.js 函数REVEAL_CELL

问题出在Cell.vue,问题是您正在检查一个不变的变量以确定显示的状态。 您已将this.cell.isRevealed抽象为一个名为 isUnrevealed 的变量,该变量从未被告知在初始加载后如何更改。

选项 1

isUnrevealed似乎是一个不必要的便利变量。 如果删除isUnrevealed并将对它的引用更改为 !cell.isRevealed ,则代码将按预期工作。

选项 2

如果你设置使用此变量,请将其更改为计算变量,以便在 Vuex 状态传播对 cell isRevealed prop 的更改时,它会不断更新自身:

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

如果采用此路线,请不要忘记从data中删除属性,并在mounted(第一行(中删除分配。


您也会遇到同样的问题 isMinecellStyle . 因此,完全删除datamounted并使它们也都计算出来。

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}`;
      }
    }
  }
}

最新更新