Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is namespacing of modules in vuex

Tags:

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.

like image 369
Abdullah Khan Avatar asked Dec 13 '17 11:12

Abdullah Khan


People also ask

What is Namespacing in Vuex?

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.

What is the purpose of the dynamic module registration in Vuex?

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.

What is the use of mapState in Vuex?

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.

How do you commit a mutation from another module Vuex?

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 .


1 Answers

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.

like image 181
Tomer Avatar answered Oct 08 '22 02:10

Tomer