⚠️ 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 7 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.

Matthew
Matthew
~ 6 years ago

The namespaces should be created like this now (https://github.com/ktsn/vuex-class):

const Login = namespace('login')```

and used like this:

```@Login.State login!: LoginState
@Todo.Getter todos!: Todo[] 
@Todo.Getter dones!: Todo[] ```

Note that the lazy loading of the login state module causes problems with the namespace creation as shown above. This had to be removed to get this to work.

Would be great if Alex could update the example and show how this works with lazy loading too.
Markdown supported.
Become a member to join the discussionEnroll Today