【问题标题】:Array not reactive if I modify individual elements of it如果我修改它的单个元素,数组不会反应
【发布时间】:2019-01-27 13:01:39
【问题描述】:

这是 Vuex store 中的一个变异方法。我能够执行注释代码并查看组件中的更改,但不能查看未注释的部分。

看起来该状态仅在我使用 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);
            }

【问题讨论】:

    标签: typescript vue.js vuex


    【解决方案1】:

    解决了。

    https://vuejs.org/v2/guide/list.html#Array-Change-Detection

    VueJS 不会对突变做出反应,例如:

    vm.items[indexOfItem] = newValue
    

    必须这样做:

    Vue.set(vm.items, indexOfItem, newValue)
    

    【讨论】:

      【解决方案2】:

      通常,在处理复杂的对象数组时,我splice 数组并将其替换为更新的数组。并且 Vue 可以看到变化。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-10
        • 1970-01-01
        • 2023-04-06
        • 2014-05-05
        • 1970-01-01
        • 2014-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多