The pitfalls encountered when using modules vuex
Actually, it's not a trick, I just didn't pay attention to the official API. When defining the module, I need to add a namespace to the module namespaced: true
attribute, otherwise the naming cannot be exposed, resulting in errors such as [vuex] module namespace not found in mapState().
Basic usage of modules in vuex
1. store file structure
- src - components - store - -modules - -
2.1 - Manually introduce modules
import Vue from 'vue' import Vuex from 'vuex' import bus from './module/bus' import app from './module/app' (Vuex) export default new ({ state: { // Here is the root vuex state }, mutations: { // Here is the root vuex state }, actions: { // Here is the root vuex state }, modules: { // Sub-vuex status module registration namespaced: true, // In order to solve the problem of naming conflicts between different modules app, bus } })
2.2 - Dynamic introduction of modules
import Vue from 'vue' import Vuex from 'vuex' (Vuex) const dynamicModules = {} const files = ('.', true, /\.js$/) const dynamicImportModules = (modules, file, splits, index = 0) => { if (index == 0 && splits[0] == 'modules') { ++index } if ( == index + 1) { if ('index' == splits[index]) { modules[splits[index - 1]] = files(file).default } else { [splits[index]] = files(file).default } } else { let tmpModules = {} if ('index' == splits[index + 1]) { tmpModules = modules } else { modules[splits[index]] = modules[splits[index]] ? modules[splits[index]] : {namespaced: true, modules: {}} tmpModules = modules[splits[index]] } dynamicImportModules(tmpModules, file, splits, ++index) } } ().filter(file => file != './').forEach(file => { let splits = (/(\.\/|\.js)/g, '').split('\/'); dynamicImportModules(dynamicModules, file, splits) }) export default new ({ modules: dynamicModules, strict: .NODE_ENV !== 'production' })
3. File content
const state = { user: {}, // Status data that needs to be managed} const mutations = { setUser (state, val) { = val } } const getters = {} const actions = {} export default { namespaced: true, state, mutations, getters, actions }
4.1 Use the page
// When using mutations, getters, and actions in the module, add the module name, for example, when using commint to execute mutations// Format: Module name/mutations in the modulethis.$("app/setUser", user) // Also add the module name when obtaining attributesthis.$
Used in 4.2
// Introduce the store here is equivalent to this.$store in the pageimport store from '@/store' export const setCurUser = (user) => { let curUser = if(!curUser) { ("app/setUser", user) return user } return curUser }
5. Configuration
import Vue from 'vue' import App from './App' import router from './router' import store from './store' new Vue({ el: '#app', router, store, render: h => h(App) })
The above is personal experience. I hope you can give you a reference and I hope you can support me more.