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 modules right.
Can anybody put some light on namespaces in a better way? When/why to use it?
Much appreciated.
In the previous Vuex tutorial, we learned that by default, getters, actions, and mutations inside modules are registered under the global namespace, which allows multiple modules to react to the same mutation or action.
Dynamic module registration makes it possible for other Vue plugins to also leverage Vuex for state management by attaching a module to the application's store. For example, the vuex-router-sync library integrates vue-router with vuex by managing the application's route state in a dynamically attached module.
Mapping State Vuex provides a helper function called mapState to solve this problem. It is used for mapping state properties in the store to computed properties in our components. The mapState helper function returns an object which contains the state in the store.
To change another module state from one module in Vuex, we can call commit with the mutation name with the root option set to true . commit("TOGGLE_LOADING", null, { root: true }); to call commit to commit the TOGGLE_LOADING mutation with root set to true .
When you have a big app with a very large state object, you will often divide it into modules.
Which basically means you break the state into smaller pieces. One of the caveats is that you can't use the same method name for a module since it is integrated into the same state, so for example:
moduleA { actions:{ save(){} } } moduleB { actions:{ //this will throw an error that you have the same action defined twice save(){} } }
So in order to enable this you have the option to define the module as namespaced, and then you can use the same method in different modules:
moduleA { actions:{ save(){} }, namespaced: true } moduleB { actions:{ save(){} }, namespaced: true }
and then you call it like this:
this.$store.dispatch('moduleA/save') this.$store.dispatch('moduleB/save')
Please note that it might complicate things a bit if you're using mapGetter
or mapActions
since the getters are now in the form of ['moduleA/client']
So use it only if you really need to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With