Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set global mutation in module vuex js store

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.

like image 628
Василий Буторин Avatar asked Jun 27 '17 18:06

Василий Буторин


1 Answers

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.

like image 195
thanksd Avatar answered Oct 16 '22 11:10

thanksd