I have recently started with vuex
.
The official docs explains well what modules are but i am not sure if i understood the namespaces in mo
By default, Vuex registers all getters, actions in the global namespace. The global Vuex namespace will face the conflicts as the Vuex modules grow in large numbers. The namespacing approach comes into picture the resolve this issue. The namespaced module won't get registered in the global namespace. instead, it's available under the specific module namespace
.
Consider the example having two module products and cart,
//products module
export default {
namespaced: true,
state: {
products: []
},
getters: {
products(state){
return state.products
}
},
actions: {
async load(context, params){ ... }
},
mutations: {
products(state, data){ ... }
}
}
and another module having similar getters and actions,
//cart module
export default {
namespaced: true,
state: {
products: [],
cart: []
},
getters: {
products(state){ return state.products }
cart(state){ return state.cart}
},
actions: {
async load(context, params){ ... },
async set(context, params){ ... },
},
mutations: {
products(state, data){ ... },
cart(state, data){ ... }
}
}
Both products
and cart
module have a getter product and action load in common. If you use such a module without namespacing, it will create issues. Here making namespaced: true
in the root of the module helps to recover such a situation.
You can map the getters using namespace as ...mapGetters(['products/products'])
and same applies for mapActions
too.