vuex 如何動態(tài)引入 store modules
動態(tài)引入store modules
主要解決的問題每次建一個module需要自己去主index.js里面去注冊
為了偷懶,也為了避免團(tuán)隊(duì)開發(fā)時同時對index.js 進(jìn)行修改引發(fā)沖突
所以在index.js中 動態(tài)的對子目錄和模塊進(jìn)行注冊
我的目錄結(jié)構(gòu)是

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時遇到的坑
其實(shí)也不算坑,只是自己沒注意看官網(wǎng)api,定義module另外命名時,需要在module中加一個命名空間namespaced: true
屬性,否則命名無法暴露出來,導(dǎo)致報[vuex] module namespace not found in mapState()等錯誤。
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue.js 雙層嵌套for遍歷的方法詳解, 類似php foreach()
今天小編就為大家分享一篇vue.js 雙層嵌套for遍歷的方法詳解, 類似php foreach(),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
Vue3+Vite+TS實(shí)現(xiàn)二次封裝element-plus業(yè)務(wù)組件sfasga
這篇文章主要介紹了在Vue3+Vite+TS的基礎(chǔ)上實(shí)現(xiàn)二次封裝element-plus業(yè)務(wù)組件sfasga,下面文章也將圍繞實(shí)現(xiàn)二次封裝element-plus業(yè)務(wù)組件sfasga的相關(guān)介紹展開相關(guān)內(nèi)容,具有一定的參考價值,需要的小伙伴可惡意參考一下2021-12-12
vue.extend與vue.component的區(qū)別和聯(lián)系
這篇文章主要介紹了vue.extend與vue.component的區(qū)別和聯(lián)系,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值 ,需要的朋友可以參考下2018-09-09
基于vue開發(fā)的在線付費(fèi)課程應(yīng)用過程
這篇文章主要介紹了基于vue開發(fā)的在線付費(fèi)課程應(yīng)用過程,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2018-01-01
Element Cascader 級聯(lián)選擇器的使用示例
這篇文章主要介紹了Element Cascader 級聯(lián)選擇器的使用示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07

