Skip to content

Instantly share code, notes, and snippets.

@Skinner927
Last active January 27, 2023 11:56
Show Gist options
  • Save Skinner927/7358a0cdf6156d65e0363ce3bd6e93aa to your computer and use it in GitHub Desktop.
Save Skinner927/7358a0cdf6156d65e0363ce3bd6e93aa to your computer and use it in GitHub Desktop.
Vuex Cheat Sheet

Vuex Cheat Sheet

new Vuex.Store({
  modules: {
    counter: {
      state: {
        count: 0,
      },
      getters: {
        square(state) {
          return state.count * state.count
        }
      },
      mutations: {
        increment(state) {
          state.count++;
        },
        setNewValue(state, newValue) {
          state.count = newValue;
        },
      },
      actions: {
        getCountFromApi({ commit }) {
          return someApi.getCount()
            .then((newCount) => {
              commit('setNewValue', newCount);
            });
        },
      },
    },
    // More modules ...
  },
});

State

State is the storage layer.

Never manipulate state directly, use a mutation or action for that.

Example accessing the store from a component:

const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return this.$store.state.counter.count;
    }
  }
}

Accessing State

import store from '../store';

console.log(store.state.counter.count);
// in a component method
console.log(this.$store.counter.count);

Getters

Retrieve computed derived state based on the store.

Getter functions receive the following positional arguments:

state,       // will be module local state if defined in a module.
getters,     // module local getters of the current module
rootState,   // global state (only available in a module)
rootGetters  // all getters (only available in a module)

Getting a Getter

Root level access:

console.log(store.getters.fooBar);

Method style:

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

Module access:

console.log(store.getters['counter/square']);

Mutations

The only way to change state is through a mutation. Mutations are synchronous.

Mutation functions in the Store receive positional arguments:

  • state - Current local state
  • payload - Optional payload is whatever (if anything) is passed to commit()'s second argument.

To dispatch actions or commit mutations in the global namespace, pass { root: true } as the 3rd argument to dispatch and commit.

Mutation functions edit state directly.

mutations: {
  increment(state) {
    state.count++;
  },
},

Commit a Mutation

To invoke a mutation, use the commit() function.

this.$store.commit('counter/increment');
// With a payload of 22
this.$store.commit('counter/setNewValue', 22);

Actions

Actions are like asynchronous mutations.

  • Instead of mutating the state, actions commit mutations.
  • Actions can contain arbitrary asynchronous operations.
  • Return a promise.

Action functions receives positional arguments context and payload.

context looks like this:

{
  state,      // same as `store.state`, or local state if in modules
  rootState,  // same as `store.state`, only in modules
  commit,     // same as `store.commit`
  dispatch,   // same as `store.dispatch`
  getters,    // same as `store.getters`, or local getters if in modules
  rootGetters // same as `store.getters`, only in modules
}

payload is optional if passed as the second argument to dispatch().

To dispatch actions or commit mutations in the global namespace, pass { root: true } as the 3rd argument to dispatch and commit.

Actions should commit any changes via a mutation.

const actions = {
  getCountFromApi({ commit }) {
    return someApi.getCount()
      .then((newCount) => {
        commit('setNewValue', newCount);
      });
  },
};

Dispatch

Dispatch can also take a payload as a second argument.

this.$store.dispatch('counter/getCountFromApi');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment