Get the App
SLTechnology News&Howtos  ›  Development  › 

How to introduce store modules dynamically into vuex

Shulou Source: shulou.com Published: 2022-06-01 02:25:36 09月16日 Update

This article mainly shows you "how to introduce vuex dynamically into store modules", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to introduce vuex dynamically into store modules" this article.

Dynamic introduction of store modules

The main problem to be solved is that you need to register in the main index.js to build a module each time.

In order to be lazy, but also to avoid conflicts caused by simultaneous changes to index.js during team development.

So register subdirectories and modules dynamically in index.js

My directory structure is

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 [[index-1]] = files (file). Default} else {modules.modules.modules [splits] = files (file). }} else {let tmpModules = {} if ('index' = = splits [index + 1]) {tmpModules = modules} else {modules [splits] = modules [index]? Modules [splits]: {namespaced: true, modules: {}} tmpModules = modules [splits]} 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'}) encountered when using modules

In fact, it's not a pit. I just didn't pay attention to the official website api. When defining module and naming it separately, you need to add a namespace namespaced: true in module.

Property, otherwise the naming cannot be exposed, resulting in errors such as reporting [vuex] module namespace not found in mapState ().

The above is all the content of the article "how to introduce store modules dynamically into vuex". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Dynamic content article catalog learning help just at the same time team pair attribute easy to understand more organization module viewer knowledge space structure ribbon Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux OPPO Reno Xiaomi MySQL Apple