[英]Mutation function doesn't affect state variable
In one of my store modules ( modal.js
) I have a dialog state variable and a setDialogState
mutation that assigns a value to dialog
. 在我的一个存储模块(
modal.js
)中,我有一个对话框状态变量和一个setDialogState
变量,该变量将一个值分配给dialog
。
When calling setDialogState
from my component, dialog
value doesn't change. 从我的组件调用
setDialogState
, dialog
值不会更改。 I know it because the value of this.$store.state.modal.dialog
hasn't changed and also Vue Devtools extension shows the same old value for dialog
. 我知道这是因为
this.$store.state.modal.dialog
的值未更改,并且Vue Devtools扩展也显示了dialog
旧值。
What's going on? 这是怎么回事?
In my store module store/modules/modal.js
: 在我的商店模块
store/modules/modal.js
:
const state = {
dialog: false
}
const mutations = {
setDialogState (state, payload) {
this.state.dialog = payload;
console.log(this.state.dialog); // strangely, this correctly logs the new value
}
}
export default {
namespaced: true,
state,
mutations
}
And in my component: 在我的组件中:
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
dialog: state => state.modal.dialog
})
},
mounted() {
console.log(this.$store.state.modal.dialog);
this.$store.commit('modal/setDialogState', true);
setTimeout(()=> {
console.log(this.$store.state.modal.dialog);
}, 2000); // this should log the new value, yet it still logs the old value
}
}
</script>
You are trying to access to state
by reference of this
, there u can't apply mutation of your state. 您试图访问
state
通过引用this
,有你无法套用您的状态突变。 The mutation mechanism is made to get the state
in every function, then just have to use it as local variable inside of the current function. 使突变机制获取每个函数的
state
,然后只需将其用作当前函数内部的局部变量即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.