This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Call a Root Vuex Mutation or Action from within a Module in TypeScript

    Alex Jover MoralesAlex Jover Morales

    Everything in a Vuex Module is local to itself: the State, Mutations, Actions, Getters. But sometimes you need to call something from the outside. This lesson shows how you can call an external Mutation and Action from within a module in TypeScript.

    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

    Aside from modules, we can also have our rootState mutations, actions, and getters. Let's write account state. TypeScript is complaining because the rootState doesn't have account property, and it's inferring it from the modules.

    You go to LoginModule, you see there we are setting the rootState to second parameter of the module type. To fix it, go to types and add account property as a number to the rootState. Now let's try it on mutation. Call it sum, and it will take the state and sum it up by one.

    The way we can trigger a real mutation from a module is by using an action. If we go to the todos module, we had defined an action there to add that todo asynchronously, and here we commit an app todo mutation.

    From here, if we write commit sum, we would be triggering a todos/sum mutation because this module is in that space. In order to fix that, we can provide a third parameter which is annotate, and there defined root:true.

    In that way, we'd be triggered with the namespace. Let's try this. We add an assigned todo here, and we'll see that the sum mutation has been triggered and the count state has been increased. The same applies to other modules, mutation, or actions.

    For example, you could say login/login, and you will be triggering the login mutation from the login module. Let's try this again, and you'll see the mutation is triggered, and we see up there the name.

    In order to dispatch actions, the contest parameter of an action give us a dispatch function. It has the same signature than commit. First parameter will be the action name, the second the payload, and in the third we can indicate root:true, so it will be triggered without the namespace.

    Discuss

    Discuss