/* module.js */ import alarm from './modules/alarm' import history from './modules/history' import factory from './modules/factory' import contact from './modules/contact' import company from './modules/company'; import deviceManage from './modules/device-manage' import deviceModel from './modules/device-model' import deviceActivation from './modules/device-activation' import user from './modules/user' import role from './modules/role' import setAlarm from './modules/setAlarm' import factoryMode from "./modules/factoryMode"; import ScreenDeviceWatch from './modules/screen-device-watch' import ScreenDeviceForecast from './modules/screen-device-forecast' export default { alarm, company, deviceManage, deviceModel, user, factory, contact, deviceActivation, history, role, setAlarm, factoryMode, ScreenDeviceWatch, ScreenDeviceForecast, } /* index.js */ import Vue from 'vue' import Vuex from 'vuex' import state from './state' import getters from './getters' import modules from './modules' import actions from './actions' import mutations from './mutations' Vue.use(Vuex) export default new Vuex.Store({ state, getters, mutations, actions, modules })
可以发现每个模块都要我们手动导入,然后加入到module里面,如此重复。当模块不多还好,假如项目大了,有50个模块,那就得要做很多重复的工作。
跟注册组件一样,我们还是利用require.context来实现。
/** * 读取./modules下的所有js文件并注册模块 */ const requireModule = require.context('./modules', false, /\.js$/) const modules = {} requireModule.keys().forEach(fileName => { const moduleName = fileName.replace(/(\.\/|\.js)/g, '') modules[moduleName] = { namespaced: true, ...requireModule(fileName).default } }) export default modules /* index.js */ import Vue from 'vue' import Vuex from 'vuex' import modules from './modules' Vue.use(Vuex) export default new Vuex.Store({ state, getters, mutations, actions, modules })
这篇关于如何写出更优雅的vue.js代码的文章就介绍到这了,希望大家以后多多支持脚本之家。
您可能感兴趣的文章: