Cheatsheet Vuex

Vuex é um padrão de gerenciamento de estado + biblioteca para aplicativos Vue.js.

Criando Loja

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
,
})

Incluir loja no aplicativo

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

Usando em .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>