This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Update Vuex State with Mutations and MapMutations in Vue.js

1:49 Vue.js lesson by

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.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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.

Avatar
Sergey

I don't see how store/index.js is included into component. Shouldn't it be explicitly imported?

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?