在我的部分,我有:
currentItem.recipecurrentItem是作为对象启动的vuex状态:
currentItem: {} 在同一个组件中,我使用mapState导入它:
...mapState('ItemStore', [
'currentItem'
])当我为它添加一个食谱时,这个突变被称为:
ADD_ITEM_RECIPE: (state, recipe) => {
state.currentItem.recipe = recipe
}recipe是从服务器到post请求的响应,以创建一个新的菜谱。
在我的组件中,我有一些v-if="currentItem.recipe",这在一开始是假的,因为currentItem没有recipe
在devtools中,我可以看到recipe被添加到currentItem中。但是组件不更新。v-if不会更改为true。在devtools中,如果我手动提交突变,它就会像预期的那样工作。
所以我试着把突变改变为:
state.currentItem.recipe = Object.assign({}, state.currentItem.recipe, recipe)但问题仍然存在。
为什么会发生这种情况,我该如何解决?
发布于 2020-05-02 03:28:35
尝试重写整个对象:
ADD_ITEM_RECIPE: (state, recipe) => {
state.currentItem = {...state.currentItem, recipe: recipe}
}发布于 2020-05-02 05:37:49
您正在向现有对象添加一个新键,因此,反应性在这方面不起作用。
@HansFelixRamos的答案是正确的,但你也有其他的选择。
Object.assign是近的,但没有雪茄。您需要更新整个对象。state.currentItem= Object.assign({}, state.currentItem, {recipe})
这将将recipe添加到新对象中,而浅层复制state.currentItem.
recipe。。
state: {
currentItem: {
//other properties
recipe: false // or null, or undefined
}
}我认为第二种方法更适合,特别是对于较长的路径对象。如果为所有键声明默认值,则不需要编写类似此const val = obj && obj.path1 && obj.path1.path2 && obj.path1.path2.path3的防御性代码来访问深度嵌套的属性。
https://stackoverflow.com/questions/61554020
复制相似问题