Reputation: 3520
I tried many things mentioned on the portal but nothing seems to work for me so posting here for some work-around.
I have 2 modules within my Nuxtjs
application folder store\modules
: ModuleA
and ModuleB
. For some verification in ModuleB
I would like to access the state
from ModuleA
but for some reason, it's failing.
I tried rootScope
, import
etc but it did not work for me.
My state/modules/ModuleA.js
:
export const state = () => ({
eventType: 'MyEvent',
})
export const mutations = {
eventTypePopulator (state, event) {
state.eventType = event
},
}
My state/modules/ModuleB.js
:
export const state = () => ({
input: {}
})
export const mutations = {
jsonPreparation ({state, rootState}, payload) {
console.log(rootState.eventType)
// console.log($store.state.ModuleA.eventType)
}
}
I tried to import ModuleA
into ModuleB
and use it but that also did not work for me. Can someone please help me how can I access the state
from one Module
in another Module
within Nuxtjs/Vuejs
Upvotes: 2
Views: 1140
Reputation: 46676
As shown in the API reference, rootState
is available in actions
and getters
.
It did not found any way of using it directly into a mutation
.
Meanwhile, this can be achieved by passing it as a param to the mutation
like this
ModuleB.js
const mutations = {
NICE_TASTY_MUTATION: (_state, { rootState, payload }) => {
// _state is not used here because it's moduleB's local state
rootState['moduleA'].eventType = payload
},
}
const actions = {
async myCoolAction({ commit, rootState }, { ...}) {
commit('NICE_TASTY_MUTATION', {
rootState,
payload: 'some-stuff'
})
}
}
And this could be called in a .vue
file with something like this
methods: {
...mapActions('ModuleB', ['myCoolAction']),
}
...
await this.myCoolAction()
PS: IMO the convention is more to name the file module_b.js
.
Upvotes: 1