Skip to content

Instantly share code, notes, and snippets.

@bsimpson
Last active September 27, 2019 16:03
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 bsimpson/77e397e07aab3671c82ec37548d688e5 to your computer and use it in GitHub Desktop.
Save bsimpson/77e397e07aab3671c82ec37548d688e5 to your computer and use it in GitHub Desktop.
Proposal for Vuex Store Best Practices

Goals

  • Consistency - Standardize state/getter/mutation naming
  • Easier to read - less boilerplate by accessing literal properties without constants, reducing unnecessary getters
  • Organization - Any helper functions go inside getter/mutation/action context - not at top level

State

In Store

  • Create a property name on the state object with a default value
  • Keep in mind we will prefix this property name get* for getters, set* for mutations (setters)
state: {
  editModeEnabled: false,
}

In Test

it('defaults to false', () => {
  expect(store.state.profiles.editModeEnabled).to.eql(false);
});

In Component

  • If no getter is needed, you can use property access to read the state:
$store.state.profiles.editModeEnabled

Mutation

In Store

  • No constants
  • Define mutation as:
mutations: {
  setEditModeEnabled(state, arg) {
    state.editModeEnabled = arg
  }
}

In Test

it('sets to true', () => {
  store.commit('profiles/setEditModeEnabled', true);
  expect(store.getters['profiles/getEditModeEnabled']).to.eql(true);
});

In component

  • No import { mapMutations }
  • No import of constants
  • No mapMutations(<namespace>, { ... } methods
  • Define mutation call as:
$store.commit('<namespace/property>', args )
# e.g. $store.commit('profiles/setEditModeEnabled')

Getters

  • DO NOT IMPLEMENT if the getter reads the state with no other logic
  • If get logic is needed, name the getter get<state property> e.g. getEditModeEnabled

In Store

  • Define getter (if logic is needed) as:
getters: {
  getEditModeEnabled: state => {
    return !!state.editModeEnabled;
  }
}

In Test

it('returns false', () => {
  expect(store.getters['profiles/getEditModeEnabled']).to.eql(false);
});

In Component

  • No import { mapGetters }
  • No import of constants
  • No mapGetters(<namespace>, {}) methods
  • Implement using property style access as:
$store.getters['profiles/getEditModeEnabled']

Actions

Only use for async calls, or chaning multiple mutations. Everything else should be a mutation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment