I need to be able to change the state of the global variable alert from any Vuex module.
store/index.js:
export const state = () => ({
alert: null
})
store/child.js:
export const mutations = {
SET_ALERT: function (rootState, alert) {
rootState.alert = alert
}
}
export const actions = {
setalert({commit}){
commit('SET_ALERT', 'warning')
}
}
I want to call setalert and set the global store.state.alert to "warning". Currently, store.state.child.alert is getting set to "warning" instead.
You cannot access the state of a vuex module from within another module's mutation.
Right now your SET_ALERT mutation is referencing the child state because it is within the child module's scope. Changing the parameter name of the state object to rootState won't change what it is.
But, you can simply move the SET_ALERT mutation to be in the index.js file. The mutation can still be called from the child module's setalert action.
If you are using namespacing for the module (namespace: true), you will need to explicitly say to use the root module in the commit call, like so:
commit('SET_ALERT', 'warning', { root: true });
Here's the documentation for Vuex Modules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With