vuex 如何动态引入 store modules
作者:qq_489366879 时间:2024-04-30 08:45:44
动态引入store modules
主要解决的问题每次建一个module需要自己去主index.js里面去注册
为了偷懒,也为了避免团队开发时同时对index.js 进行修改引发冲突
所以在index.js中 动态的对子目录和模块进行注册
我的目录结构是
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const dynamicModules = {}
const files = require.context('.', true, /\.js$/)
const dynamicImportModules = (modules, file, splits, index = 0) => {
if (index == 0 && splits[0] == 'modules') {
++index
}
if (splits.length == index + 1) {
if ('index' == splits[index]) {
modules[splits[index - 1]] = files(file).default
} else {
modules.modules[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)
}
}
files.keys().filter(file => file != './index.js').forEach(file => {
let splits = file.replace(/(\.\/|\.js)/g, '').split('\/');
dynamicImportModules(dynamicModules, file, splits)
})
export default new Vuex.Store({
modules: dynamicModules,
strict: process.env.NODE_ENV !== 'production'
})
使用modules时遇到的坑
其实也不算坑,只是自己没注意看官网api,定义module另外命名时,需要在module中加一个命名空间namespaced: true
属性,否则命名无法暴露出来,导致报[vuex] module namespace not found in mapState()等错误。
来源:https://blog.csdn.net/qq_32352565/article/details/103698739
标签:vuex,动态引入,store,modules
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Go语言标准库之strconv的使用
2024-04-23 09:42:56
Python中三种时间格式转换的方法
2023-10-18 13:11:43
![](https://img.aspxhome.com/file/2023/2/100932_0s.png)
python 解析XML python模块xml.dom解析xml实例代码
2022-11-24 15:15:09
python numpy 显示图像阵列的实例
2022-09-23 01:24:13
![](https://img.aspxhome.com/file/2023/1/112791_0s.jpg)
Python实现的井字棋(Tic Tac Toe)游戏示例
2023-03-08 23:22:34
![](https://img.aspxhome.com/file/2023/9/133689_0s.jpg)
asp 简单分页代码
2011-03-11 10:53:00
全面理解JavaScript中的闭包
2024-04-17 10:09:24
![](https://img.aspxhome.com/file/2023/2/136352_0s.png)
SQL Server误区30日谈 第1天 正在运行的事务在服务器故障转移后继续执行
2024-01-14 22:53:03
客齐集社区头像显示效果代码
2008-04-03 13:15:00
![](https://img.aspxhome.com/file/UploadPic/20084/3/200843132357900s.gif)
python画环形图的方法
2023-02-12 09:54:24
![](https://img.aspxhome.com/file/2023/2/66742_0s.jpg)
python scipy.misc.imsave()函数的用法说明
2022-11-01 13:04:24
微信小程序实现录音
2024-04-22 13:25:41
![](https://img.aspxhome.com/file/2023/4/135694_0s.jpg)
javascript操作table(insertRow,deleteRow,insertCell,deleteCell方法详解)
2024-04-16 09:14:08
scrapy爬虫完整实例
2021-06-08 09:34:26
python PyGame五子棋小游戏
2023-09-29 13:32:45
![](https://img.aspxhome.com/file/2023/2/95862_0s.png)
基于Python中isfile函数和isdir函数使用详解
2023-05-10 00:46:50
Python采集王者皮肤图片实战示例
2021-08-02 12:09:23
![](https://img.aspxhome.com/file/2023/7/106967_0s.jpg)
jquery 禁止鼠标右键并监听右键事件
2024-02-23 14:34:19
浏览器右下角弹出提示窗口
2008-10-30 12:37:00
Python Pillow Image.save 保存为jpg图片压缩问题
2023-07-05 11:13:49