I tried to understand what a rootState
is with vuejs, vuex ... but couldn't find clear explanation (google, or other forums) with these key words:
Can anyone explain what is it, and how we take advantage of its usage ?
To better structure your code, you can split the vuex store in different modules. See the reference on that.
Here an example of my store in a project I'm currently working on:
In my project I need several data from an API so I decided to split my store after this API response to bundle all functionalities that belongs together in one module. The index.js
is used to put all the modules togehter and export the store:
...
import categories from './modules/categories'
import transportation from './modules/transportation'
import insurances from './modules/insurances'
import booking from './modules/booking'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
categories,
transportation,
insurances,
booking
},
state: {
// here I have general stuff that doesn't need to be split in modules
},
mutations: {
// general stuff
},
actions: {
// general stuff
},
strict: true
})
The rootState
gets important if I need to access the general stuff in the index.js
or if I want to access data from a module from inside another module.
E.g.:
To put a booking I need to know which categorie is selected from the current user of my app. To achive this I simply can use the rootState
prop in the action:
/modules/categories.js
export default {
namespaced: true,
state: {
categories: [ // data I need acces to ]
}
/modules/booking.js
actions: {
async PUT_BOOKING({ state, commit, dispatch, rootState }) {
// access categories
const categories = rootState.categories.categories
// rootState -> access root
// categories -> namespaced module in store
// categories -> state categorie in namespaced module
}
}
You can for example also pass rootGetters
to an action. In my example I have a getter
in my categories module that return the index of the currently selected categorie from the categorie array (=state
prop).
async PUT_BOOKING({ state, commit, dispatch, rootState, rootGetters }) {
// access categories
const categories = rootState.categories.categories
// acces index of selected categorie
const index = rootGetters['categories/selCategorie']
}
Hopefully my example was understandable and I could help you a little.