In one of my store modules ( modal.js
) I have a dialog state variable and a setDialogState
mutation that assigns a value to dialog
.
When calling setDialogState
from my component, dialog
value doesn't change. 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
.
What's going on?
In my store module 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.