奇怪的异常现象。当我首先执行“撤消”操作时,对象/组件属性 this.gridTiles
确实被正确设置。但是当我执行“重做”操作(参见下面的代码)时,我无法将 this.gridTiles
设置为新值!它似乎保留了旧的值(value)。 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');
}
},
最佳答案
这可能不是正确的答案,也许应该是一条评论,但评论太长,所以我会在这里发布。希望这有帮助:
代码:
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
上下文?
您应该在 setCurrentEntireState
中记录 this
以检查它是否确实是该组件。
关于javascript - 无法更改 Vue 组件的对象属性(真正的异常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56294292/