Vuex

https://vuex.vuejs.org/en/

Overview

npm install vuex
src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import * as getters from './getters'
import * as actions from './actions'
import * as mutations from './mutations'

Vue.use(Vuex);

const STRICT = process.env.NODE_ENV !== 'production';

const store = new Vuex.Store({
  state,
  getters,
  actions,
  mutations,
  strict: STRICT,
})

if (module.hot) {
  module.hot.accept([
    './getters',
    './actions',
    './mutations',
  ], () => {
    store.hotUpdate({
      getters: require('./getters'),
      actions: require('./actions'),
      mutations: require('./mutations'),
    })
  })
}
src/main.js
import Vue from 'vue'
import store from './store'

new Vue({
  el: '#app',
  store,
})
computed: {
  localComputed () { /* ... */ },
  // mix this into the outer object with the object spread operator
  ...mapState({
    // ...
  })
}
state
  • the single source of truth.
  • *Can exist only one store for each application
  • like data in components
getters
  • like computed in components
mutations
  • methods which mutates the state. Must be synchronous
actions
  • methods which commit mutations. Can be asynchronous
  • the handler is called with context, which contains store essentials like state, commit, and getters.
modules
  • all elements withn modules references their own localState by default.
  • Note rootState, namespace for interactions between the store and other modules

vuex-persistedstate

// Persists all vuex states in localStorage
export default new Vuex.Store({
  // ...
  plugins: [createPersistedState()],
});
// Selective both states and storages
export default new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production',
  plugins: [createPersistedState({
      storage: window.localStorage,
      paths: [
        'auth.me',
        'auth.avatarURL',
      ],
    }),
    createPersistedState({
      storage: window.sessionStorage,
      paths: [
        'auth.refresh',
      ],
    }),
  ],
  modules: {
    auth,
    main,
  },
});