Join egghead, unlock knowledge.

Want more egghead?

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

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Update Vuex State with Mutations and MapMutations in Vue.js


    You commit changes to state in Vuex using defined mutations. You can easily access these state mutations in your template using mapMutations. This lesson shows you have to wire together your Vue.js template with your Vuex store using mutations and mapMutations.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    To change this counter value in my store here, my store/index file, I'll export a const of mutations. This is an object which declares some functions. I'm going to declare increment, and increment takes in the state. It references state-dot-whatever properties I need, like counter.

    I'm going to say ++, so when we call increment, it's going to take the state referencing this state, and increment that value. To do that from our view, we're going to do something very similar, where I say map mutations.

    I can grab those methods off of the mutations. Inside of the methods property in my component, I can go ahead and spread a map mutations call. This takes an array of strings which map to increment, or any of the other mutations that are named inside of your mutations.

    Basically, this means that now, instead of calling any sort of store.dispatch, or referencing the store at all, I could come up here and create a button. Say, when I click on this button, call increment, and I'll just say this is a plus sign. Let's save here. I'll click plus.

    You can see this value going up. To see that process in reverse, let's just go ahead and create another button. I'll call this one minus. I'll say when I click on this, I want this to decrement. Decrement wants to be mapped to a mutation down here. Say decrement.

    I need to define that mutation in here, called decrement, which takes in a state, and says state.counter--. I'll hit save here, +++, ---, where the click handler here of increment is mapped to increment on the store, which is defined here, where the mutation tells the state to increment, or the decrement mutation tells the state to decrement.