Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing Vuex Chapter 8

mutations

Let's move on to mutations. mutations are methods that perform modifications to the


state of the store. We will define the mutations just as we defined getters.


In store.js, add the following lines:


import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
count: 0
}

const getters = {
fetchCount: state => state.count
}

const mutations = {
increment: state => state.count++,
decrement: state => state.count--
}

export const store = new Vuex.Store({
state,
getters,
mutations
})

We added two different mutation functions in the preceding code. The increment


method increments the count by 1, whereas the decrement method decreases the count by



  1. This is where we introduce actions.


Actions

Actions are the methods that dispatch mutation functions. Actions perform mutations.


Since actions are asynchronous and mutations are synchronous, it's always a good


practice to use actions to mutate the state. Now, just like getters and mutations, let's


define the actions as well. In the same file, that is, store.js, add the following lines of


code:


import Vue from 'vue'
import Vuex from 'vuex'
Free download pdf