Skip to content

Instantly share code, notes, and snippets.

@unstoppablecarl
Last active June 17, 2020 14:59
Show Gist options
  • Save unstoppablecarl/433ed5758dbabc3fc1730b05c4b5de5a to your computer and use it in GitHub Desktop.
Save unstoppablecarl/433ed5758dbabc3fc1730b05c4b5de5a to your computer and use it in GitHub Desktop.
How I use vuex
// within a vue component only use mapGetters, mapActions, or this.$store.dispatch(...)
// never directly reference state or mutations from within a vue component
// clearly shows what state data should be exposed and should be internal
import Vue from 'vue'
import Record from '...'
import api from '...'
const store = {
state: {
foo: true,
bar: 99,
records: {},
},
mutations: {
...mapDefaultMutations({
setFoo: 'foo',
setBar: 'bar',
}),
setRecord(state, record) {
Vue.set(state.records, record.id, Record.parseOrFail(record))
},
setRecords(state, records) {
records.forEach((record) => {
Vue.set(state.records, record.id, Record.parseOrFail(record))
})
},
destroyRecord(state, { id }) {
Vue.delete(state.records, id)
},
},
// components only change state via actions
// remember that actions always return a promise even if your method does not
actions: {
// setFoo({ commit }, value) {
// commit('setFoo', value)
// return Promise.resolve()
// },
// replaces code above
...mapDefaultActions([
'setFoo',
'setBar',
]),
fetchRecords({ commit, dispatch }) {
return api.fetch()
.then((records) => {
commit('setRecords', records)
})
},
createRecord({ commit, dispatch }, payload) {
return api.create(payload)
.then((record) => {
commit('setRecord', record)
})
},
updateRecord({ commit, dispatch }, payload) {
return api.update(payload)
.then((record) => {
commit('setRecord', record)
})
},
destroyRecord({ commit, dispatch }, { id }) {
return api.destroy({ id })
.then(() => {
commit('destroyRecord', { id })
})
},
},
// components only access state via getters
getters: {
...mapDefaultGetters([
'foo',
'bar',
'records',
]),
fooAndBar(state) {
return state.foo + '-' + state.bar
},
},
}
function mapDefaultGetters(array) {
const out = {}
array.forEach((key) => {
out[key] = (state) => state[key]
})
return out
}
function mapDefaultMutations(mutations) {
const out = {}
Object.keys(mutations).forEach((mutation) => {
let property = mutations[mutation]
out[mutation] = (state, payload) => {
state[property] = payload
}
})
return out
}
function mapDefaultActions(actions) {
const out = {}
if (Array.isArray(actions)) {
actions.forEach(action => {
out[action] = ({ commit }, payload) => {
commit(action, payload)
}
})
return out
}
Object.keys(actions).forEach((action) => {
let mutation = actions[action]
out[action] = ({ commit }, payload) => {
commit(mutation, payload)
}
})
return out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment