无法更改Vue组件的对象属性(真正的异常)

时间:2019-05-24 14:05:10

标签: javascript vue.js clone

一个奇怪的异常。当我首先执行“撤消”操作时,对象/组件属性this.gridTiles的设置正确。但是,当我执行“重做”操作(请参见下面的代码)时,无法将this.gridTiles设置为新值!它似乎保持了旧的价值。 this.gridTiles是一个带有嵌套项/对象的数组。但是,在我尝试设置该值之前,如果我将其分配给test变量,它将为我提供正确的值。很奇怪!任何帮助将不胜感激!

注意:此包启用了cloneDeep():[https://www.npmjs.com/package/clone-deep]

ComponentA.vue

    data() {
        return {
            gridTiles: [],
        }
    },

....

        setCurrentEntireState(historyParams) {
            let test = cloneDeep(historyParams.gridTiles); // CORRECT VALUE
            this.test = cloneDeep(historyParams.gridTiles); // we can set this arbitrary object property correctly
            //this.gridTiles = test;    // doesn't work
            //delete this.gridTiles;    // doesn't help even if we do this first
            this.gridTiles = cloneDeep(historyParams.gridTiles); // WRONG VALUE, WHY ??
        },

        getCurrentEntireState() {  // used in saving historyStack items, not shown
            return {
                gridTiles: cloneDeep(this.gridTiles)
            }
        },

....

        EventBus.$on('refreshHistoryStateForReceiptMap', (historyParams) => {
            this.setCurrentEntireState(historyParams);
            ....
        })

ComponentB.vue

    methods: {

        ....

        undoHistoryAction() {
            let historyParams = this.$store.getters.historyStack[this.$store.getters.historyIndex - 1];
            EventBus.$emit('refreshHistoryStateForReceiptMap', historyParams);

            this.$store.commit('historyIndexDecrement');
        },

        redoHistoryAction() {
            let historyParams = this.$store.getters.historyStack[this.$store.getters.historyIndex];
            EventBus.$emit('refreshHistoryStateForReceiptMap', historyParams);

            this.$store.commit('historyIndexIncrement');
        }
    },

2 个答案:

答案 0 :(得分:1)

这可能不是正确答案,可能应该是评论,但由于太长而无法发表评论,因此我将在此处发布。希望这会有所帮助:

代码:

        setCurrentEntireState(historyParams) {
            let test = cloneDeep(historyParams.gridTiles); // CORRECT VALUE
            this.test = cloneDeep(historyParams.gridTiles); // we can set this arbitrary object property correctly
            //this.gridTiles = test;    // doesn't work
            //delete this.gridTiles;    // doesn't help even if we do this first
            this.gridTiles = cloneDeep(historyParams.gridTiles); // WRONG VALUE, WHY ??
        },

使用this的每一行都会出错。我敢打赌,这段代码:

 EventBus.$on('refreshHistoryStateForReceiptMap', (historyParams) => {
            this.setCurrentEntireState(historyParams);
            ....
        })

以某种方式弄乱了this上下文。也许放置在回调函数中,这样它会丢失组件的this上下文?

您应该在this内登录setCurrentEntireState来检查它是否确实是组成部分。

答案 1 :(得分:1)

console.log()显示的值不同于我实际使用带有断点的Chrome JS调试器时的值。另外,我在下游进行了进一步调查,发现其他一些自定义代码将值恢复为旧的/原始的。这个故事的寓意,console.log()可能并不总是正确的,或者可能有些滞后?