6yw86g
Last Updated: March 01, 2019
·
152
· waghcwb

Vuex Cheatsheet

Vuex is a state management pattern + library for Vue.js applications.

Creating Store

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

Vue.use(Vuex)
// state
const state = { count: 0 }

// types
const types = {
  INCREMENT: 'INCREMENT',
  DECREMENT: 'DECREMENT',
  RESET: 'RESET',
}

// Mutations
const mutations = {
  [types.INCREMENT]({ count }) {
    count += 1
  },
  [types.DECREMENT]({ count }) {
    count += -1
  },
  [types.RESET]({ count }) {
    count = 0
  },
}

// Actions
const actions = {
  increment({ commit }) {
    commit(types.INCREMENT)
  },
  decrement({ commit }) {
    commit(types.DECREMENT)
  },
  reset({ commit }) {
    commit(types.RESET)
  },
}

// Getters
const getters = {
  isEven({ count }) {
    return count % 2 === 0
  },
}
const store = new Vuex.Store({
  state,
  mutations,
  actions,
  getters,
})

Include store into the App

import Vue from 'vue'
import store from './store'
import App from './App.vue'
new Vuew({
  el: '#app',
  store,
  render: h => h(App),
})

Using in .Vue Templates

<template>
  <div id="app">
    <section class="hero">
        <h1 class="title">{{ "{{ count " }}}}</h1>
        <h2 v-if="isEven">Is even!!</h1>
    </section>
    <section>
      <button class="button" @click="increment">+</button>
      <button class="button" @click="decrement">-</button>
      <button class="button" @click="reset">Reset</button>
    </section>
  </div>
</template>

<script>
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'
import store from './store'

export default {
  name: 'app',
  computed: {
    ...mapState(['count']),
    ...mapGetters(['isEven']),
  },
  methods: {
    ...mapActions([
      'increment', 'decrement', 'reset',
    ]),
  },
}
</script>