想要实现vuex 模块化,直接在index.js 这样改,就可以动态导入写在camera,user文件里面的子模块
index.js 文件
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from "vuex-persistedstate" //插件数据持久化
Vue.use(Vuex)
const store = new Vuex.Store({
plugins: [createPersistedState()] //插件数据持久化
})
function registerStoreModule(module) {
const path = module.path
if (!path || store.hasModule(path)) return
const _module = Object.assign({}, module)
delete _module.path
// 加上preserveState: true 可以配置插件,数据持久化,如果没有使用vuex-persistedstate插件,就不要加上
store.registerModule(path, _module, { preserveState: true })
}
const storeContexts = require.context('./modules', true, /index\.js$/)
storeContexts.keys().forEach(name => {
registerStoreModule(storeContexts(name).default)
})
export default store
user子模块里的index.js
const user = {
path: 'user',
namespaced: true,
state: {
// 用户信息
userInfo: null,
},
mutations: {
},
actions: {
},
},
}
export default user
在入口文件,直接引入 store
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')