Skip to content

Instantly share code, notes, and snippets.

@dforesman
Created January 26, 2018 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dforesman/c298e2030013653a781eaade985e98f2 to your computer and use it in GitHub Desktop.
Save dforesman/c298e2030013653a781eaade985e98f2 to your computer and use it in GitHub Desktop.
Vuex Simple Store - helper to quickly build out simple Vuex stores, based on provided state object. Creates getters and mutations for each top-level state item (filterable). Allows augmenting and overriding.
//
// VUEX SIMPLE STORE
//
// Makes it easier to quickly build out simple stores
// - creates getters and mutations for each state item (filterable)
// - allows augmenting and overriding
//
// helper - filter out keys
const excludeKeys = (state, options) => {
// grab state keys
let keys = Object.keys(state)
// filter out any keys we want to exclude
if (options.exclude && Array.isArray(options.exclude) && options.exclude.length) {
keys = keys.filter(key => !options.exclude.includes(key))
}
return keys
}
// Makes getters for each top-level state item
// - options.exclude: state items that should not have getters made
export const makeGetters = (state, options) => {
// return object w/ getter functions for each key
return excludeKeys(state, options)
.reduce((obj, key) => {
obj[key] = localState => localState[key]
return obj
}, {})
}
// Makes mutations for each top-level state item
// - mutations accept exact value
// - options.exclude: state items to not make mutations for
export const makeMutations = (state, options) => {
// return object with value-based mutations for each key
return excludeKeys(state, options)
.reduce((obj, key) => {
obj[key] = (localState, value) => { localState[key] = value }
return obj
}, {})
}
// Makes a store given only state and actions
// - additional getters / mutations can be specified in config,
// and will override any auto-generated getters or mutations
export const simpleStore = (store, options) => {
options = {
...defaultOptions(),
...options
}
store.getters = {
...makeGetters(store.state, {
exclude: options.excludeGetters
}),
...store.getters
}
store.mutations = {
...makeMutations(store.state, {
exclude: options.excludeMutations
}),
...store.mutations
}
return store
}
// Default options for ezStore
const defaultOptions = () => {
return {
excludeGetters: [],
excludeMutations: []
}
}
export default simpleStore
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment