Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Use Namespaces in Vuex Stores using TypeScript

    Alex Jover MoralesAlex Jover Morales

    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.

    vueVue.js
    typescriptTypeScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss