Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the name of the nameSpaced vuex module inside its action or mutation?

I have multiple vuex modues with nameSpaced: true in my application. Inside the action or mutations of the modules I want to know the name of the parent module.

say I have 2 modules, 'a' and 'b', I call the mutation like

this.$store.commit("a/setName", name);
this.$store.commit("b/setName", name);

Now inside the setName function, I want to know what the calling nameSpace is ? whether it is 'a' or 'b' ?

like image 374
Neelotpal Avatar asked Apr 04 '19 10:04

Neelotpal


People also ask

What is difference between mutation and action in Vuex?

Actions are similar to mutations, the differences being that: Instead of mutating the state, actions commit mutations. Actions can contain arbitrary asynchronous operations.

What is Namespaced 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.

How do you call an action from another module Vuex?

You can call another Vuex action by passing the name of that action as a string as the first argument of dispatch : const store = new Vuex. Store({ actions: { walk(context) { context. dispatch("goForward"); }, goForward(context) { // }, }, });

How do I access Vuex store getters?

Debug the Store In any case you can call console. log(this. $store) to debug the Store. If you do so you will see the getters are prefixed with the namespace in their name.


1 Answers

Currently this is still an open issue for vuex, as you can see here: Access module namespace from within module #1244. There are a lot of workarounds for this request, but I want to show you an easy one according to your provided code.

This:

this.$store.commit("a/setName", name);
this.$store.commit("b/setName", name);

... could be this:

this.$store.dispatch('a/setName', {namespace: "a", data: name})
this.$store.dispatch('b/setName', {namespace: "b", data: name})

Yes, that means that you need to manually apply the name of that namespace you are calling, but in your example you already did it. In your action it could be something like this:

setName({commit}, object) {
        console.log(object.namespace); // submitted namespace
        commit('SET_THIS_NAME', object.data); // your data
    }

Please note, this is only a workaround, as there still isn´t an official possibility to access the namespace inside the vuex module. And so this isn´t an official way, but one way of workaround.

like image 71
StevenSiebert Avatar answered Oct 22 '22 02:10

StevenSiebert