28
loading...
This website collects cookies to deliver better user experience
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
const userModule = {
namespaced: true,
state: () => ({}),
mutations: {},
actions: {},
getters: {}
}
const organisationModule = {
namespaced: true,
state: () => ({}),
mutations: {},
actions: {},
}
const store = new VueX.Store({
modules: {
user: userModule,
organisation: organisationModule
}
})
store.state.user // -> `userModule`'s state
store.state.organisation // -> `organisationModule`'s state
namespaced
attribute is incredibly important here. Without it, actions, mutations, and getters would still be registered at the global namespace.namespaced
attribute set to true, we divide actions, mutations, and getters into the modules as well.const userModule = {
namespaced: true,
state: () => ({}),
mutations: {},
actions: {
'SET_USER'() {},
'SET_USER_LOCATION'() {}
},
getters: {}
}
store.state.user['SET_USER']() // correct ✅
stote.state['SET_USER']() // wrong ❌
mapGetters
, mapActions
, or mapMutations
to achieve that.// userModule.js
export const SET_USER = 'SET_USER'
export const SET_USER_LOCATION = 'SET_USER_LOCATION'
const userModule = {
namespaced: true,
state: () => ({}),
mutations: {},
actions: {
[SET_USER]() {},
[SET_USER_LOCATION]() {}
},
getters: {}
}
// vue file
import { mapActions } from 'vuex'
import { SET_USER, SET_USER_LOCATION } from './userModule.js'
...mapActions({
setUser: SET_USER,
setUserLocation: SET_USER_LOCATION
})
store
will be created in the root folder of our project.index.js
filemodules
folderindex.js
file, let’s see how we divide a single module. Let’s check the user
module.types.js
file. So, something like:// actions
export const SET_USER = 'SET_USER'
export const SET_USER_LOCATION = 'SET_USER_LOCATION'
// mutations
// getters
actions.js
file.actions
object within the module and export default
it, while importing the types:import { SET_USER, SET_USER_LOCATION } from './types.js'
export default {
[SET_USER]() {},
[SET_USER_LOCATION]() {}
}
index.js
(within the user module folder):import actions from './actions.js'
import mutations from './mutations.js'
import getters from './getters.js'
const state = {}
export default {
namespaced: true,
state,
actions,
mutations,
getters
}
index.js
file within the store
folder:import Vue from 'vue'
import Vuex from 'vuex'
// Modules import
import UserModule from 'modules/user'
import OrganisationModule from 'modules/organisation'
Vue.use(Vuex)
const state = {}
const actions = ({})
const mutations = ({})
const getters = ({})
const modules = {
user: userModule,
organisation: organisationModule
}
export default new Vuex.Store({
state,
actions,
mutations,
getters,
modules
})