typescript - 如果我修改它的单个元素,数组不会反应
问题描述
这是 Vuex 商店中的一种变异方法。我能够执行注释代码并查看组件中的更改,但不能查看未注释的部分。
看起来只有当我用 Array() 再次初始化它时,状态才反应。否则我看不到组件的变化,尽管状态已经改变,正如我在最后一个 console.log 中看到的那样
move(state: GameState, vector: Array<number>) {
//const piece1: Piece = new Piece(7);
//state.boardState = Array(4).fill(null).map(x => Array(4).fill(null));
//state.boardState[0][0] = piece1;
const size = state.boardState.length;
const xComponent = vector[0];
const yComponent = vector[1];
for (let i = 0; i < size - 1; i++) {
const shifter = xComponent < 0 ? size - i - 1 : i;
const shifterPrev = xComponent < 0 ? size - i - 2 : i + 1;
for (let j = 0; j < size; j++) {
if (state.boardState[shifter][j] !== null) {
if (state.boardState[shifterPrev][j] === null) {
state.boardState[shifterPrev][j] = state.boardState[shifter][j];
state.boardState[shifter][j] = null;
} else if (state.boardState[shifterPrev][j].equals(state.boardState[shifter][j])) {
state.boardState[shifterPrev][j].increaseValue();
state.boardState[shifter][j] = null;
}
}
}
}
console.log(state.boardState);
}
解决方案
解决了。
https://vuejs.org/v2/guide/list.html#Array-Change-Detection
VueJS 对突变没有反应,例如:
vm.items[indexOfItem] = newValue
它必须这样做:
Vue.set(vm.items, indexOfItem, newValue)