Overview
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
-
- Pass
store
to when new Vue({})
to reference the store as this.$store
from child components.
- Use mapState, mapGetters, as
computed
members and mapMutations, mapActions as methods
members.
- Use
mapThing
with object spread operator(...obj
) as follows:
- 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
// 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,
},
});