⚠️ This lesson is retired and might contain outdated information.

Update Vuex State with Mutations and MapMutations in Vue.js

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 2 months ago

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.

[00:00] 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.

[00:22] 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.

[00:34] 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.

[00:55] 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.

[01:10] 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.

[01:26] 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.

~ 7 years ago

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

Evan Gillogley
Evan Gillogley
~ 7 years ago

Is there any reason why we mutate over copy? Wouldn't copy be 'safer'?

Markdown supported.
Become a member to join the discussionEnroll Today