gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:15:54 25 4
gpt4 key购买 nike

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

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

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

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

这也不起作用。有人有想法吗?

我创建了一个 Codesandbox 来展示我的项目

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

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

最佳答案

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

选项 1

isUn​​revealed 似乎是一个不必要的便利变量。如果您去掉 isUn​​revealed 并将对它的引用更改为 !cell.isRevealed,代码将按预期工作。

选项 2

如果您打算使用此变量,请将其更改为计算变量,以便在 Vuex 状态将更改传播到 cell isRevealed 属性时不断更新自身:

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

关于javascript - 更新 Vuex 商店中二维数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56516335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com