⚠️ This lesson is retired and might contain outdated information.

Use Namespaces in Vuex Stores using TypeScript

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 9 months ago

Even by using modules, they still share the same namespace. So you couldn’t have the same mutation name in different modules. Namespaces solve that by prepending the path of the module to the State, Getter, Action, and Mutation.

This lesson shows how to use namespaces in Vuex modules with TypeScript.

In order to create the namespace modules, we need to add namespace:true to each module. This is a good time to type the modules. For that, we can import module from Vuex, and we need to import here as well root state.

Then we can type it with module, which is a generic that takes the state -- in this case, login state -- and the root state. Do the same in the to-dos module.

First, import module from Vuex. Then type the to-dos module with the module to-dos state and root state. Now, we get IntelliSense for the namespace.

If we run it at this point, we see everything is broken. That's normal, because what happened is before, all the getters, mutation, and actions were saved in the root namespace. For example, the DOMs getting were in the store instance.getter's DOMs.

When we add the namespace, that namespace is prepended as a path before, so to-dos/DOMs. For the case of the login mutation, now it would be in store.mutations, login/login. To solve this problem, we can use namespace from Vuex class.

Namespace is a higher order function that takes as the first parameter a module path -- for example, to-dos, or even for nested modules, to-dos/nested/whatever -- and as a second parameter, one of the Vuex class decorators -- getter, for example -- and returns a name spaced decorator.

Let's do the same for mutation and for action. Instead of getter, we have to use to-do getter for the to-do module, and the same for the to-do mutations and the action. We still need a mutation for login module, so we have to do the same, create a login mutation, and change the path to login.

Then replace it to login mutation, and this should work again. In this case, we totally isolated modules.