How to set global mutation in vuex js store module
I need to be able to change the state of a 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
gaining importance "warning"
.
source to share
You cannot access the state of the vuex module due to another mutation of the module.
Your mutation is now SET_ALERT
referencing the state child
as it is within the scope child
. Changing the name of a state object parameter to rootState
does not change its value.
But you can just move the mutation SET_ALERT
to a file index.js
. The mutation can still be called from a child
module action setalert
.
If you are using a namespace for a module ( namespace: true
), you need to explicitly specify to use the root module in the call commit
, for example:
commit('SET_ALERT', 'warning', { root: true });
source to share