vuex store

by simati

HTML

<script src="https://cdn.rawgit.com/vuejs/vue/e6d224c3c5ca3ff6a365326ba615d116764b68f2/dist/vue.js"></script>
<script src="https://cdn.rawgit.com/vuejs/vuex/cca2c4b19b7656ea4632d47c39640da68d94c239/dist/vuex.js"></script>
<div id="app">
  {{ count }}
  <button @click="increment" :disabled="locked">+</button>
  <button @click="incrementLazy" :disabled="locked">++</button>
  <button @click="decrement" :disabled="locked">-</button>
</div>

JavaScript

// actions are the business logic, can be async, call multiple actions, mutations etc.
const actions = {
	increment ({ commit }) {
    commit('MODIFY_COUNTER', { amount: 1 })
  },
  decrement ({ commit }) {
    commit('MODIFY_COUNTER', { amount: -1 })
  },
  incrementLazy ({ commit }) {
    commit('LOCK_UI')
    setTimeout(() => {
      actions.increment({ commit })
    	commit('UNLOCK_UI')
    }, 2000)
  },
}

// mutations deal with the state, nothing else
const mutations = {
	MODIFY_COUNTER (state, payload) {
  	state.count += payload.amount
  },
  LOCK_UI (state) {
  	state.locked = true
  },
  UNLOCK_UI (state) {
  	state.locked = false
  }
}

const state = {
	count: 0,
  locked: false
}

const store = new Vuex.Store({ state, actions, mutations })
new Vue({
  el: '#app',
  store,

  // alias for store.state.foo, store.state.bar etc.
  computed: Vuex.mapState(['count', 'locked']),

  // with object spread: `{...Vuex.mapActions(['increment', 'incrementLazy', 'decrement'])}`
  // without mapActions: `increment () { this.$store.dispatch('increment') }`
  methods: Vuex.mapActions(['increment', 'incrementLazy', 'decrement'])
})