Detailed explanation of Vuex modular (module) examples
This article mainly introduces Vuex modularity to you. The editor thinks it is quite good. Now I will share it with you and give you a reference. I hope it can help you.
1. Why modularization is needed
The examples we mentioned earlier are all performed in a state tree. When a project is relatively large, all states will be gathered together. Get a relatively large object, which becomes bloated and difficult to maintain. In order to solve this problem, Vuex allows us to divide the store into modules. Each module has its own state, mutation, action, getter, and can even nest modules downwards. Let's look at a typical modularization example
const moduleA = { state: {....}, mutations: {....}, actions: {....}, getters: {....} } const moduleB = { state: {....}, mutations: {....}, actions: {....}, getters: {....} } const store = new Vuex.Store({ modules: { a: moduleA, b: moduleB } }) store.state.a // moduleA的状态 store.state.b // moduleB的状态
2. The local state of the module
The mutation and getter inside the module, the first parameter (state) received is the local state object of the module, rootState
const moduleA = { state: { count: 0}, mutations: { increment (state) { // state是模块的局部状态,也就是上面的state state.count++ } }, getters: { doubleCount (state, getters, rootState) { // 参数 state为当前局部状态,rootState为根节点状态 return state.count * 2 } }, actions: { incremtnIfOddRootSum ( { state, commit, rootState } ) { // 参数 state为当前局部状态,rootState为根节点状态 if ((state.cont + rootState.count) % 2 === 1) { commit('increment') } } } }
3. Namespace (be sure to read it here, otherwise you will get tricked sometimes)
In all the above examples, the actions, mutations, and getters inside the module are registered in the global namespace. If you are in moduleA and moduleB The action, mutation, or getter (called some) with the same name is declared respectively. When you use store.commit('some'), the A and B modules will respond at the same time. So, if you want your module to be more self-contained and reusable, you can add namespaced: true to make it a namespaced module. When a module is registered, all its getters, actions, and mutations will automatically call the entire naming according to the path registered by the module. For example:
const store = new Vuex.Store({ modules: { account: { namespaced: true, state: {...}, // 模块内的状态已经是嵌套的,namespaced不会有影响 getters: { // 每一条注释为调用方法 isAdmin () { ... } // getters['account/isAdmin'] }, actions: { login () {...} // dispatch('account/login') }, mutations: { login () {...} // commit('account/login') }, modules: { // 继承父模块的命名空间 myPage : { state: {...}, getters: { profile () {...} // getters['account/profile'] } }, posts: { // 进一步嵌套命名空间 namespaced: true, getters: { popular () {...} // getters['account/posts/popular'] } } } } } })
The getters and actions that enable the namespace will receive localized getters. dispatch and commit. You do not need to add a space name prefix in the same module when using module content, and you do not need to modify the code in the module after changing the namespaced attribute.
4. Access global content (Global Assets) in the namespace module
If you want to use global state and getter, rootState and rootGetter will be passed into the getter as the third and fourth parameters. The action will also be passed in through the attributes of the context object. If you need to distribute the action or submit the mutation in the global namespace, just pass { root: true } as the third parameter to dispatch or commit.
modules: { foo: { namespaced: true, getters: { // 在这个被命名的模块里,getters被局部化了 // 你可以使用getter的第四个参数来调用 'rootGetters' someGetter (state, getters, rootSate, rootGetters) { getters.someOtherGetter // -> 局部的getter, ‘foo/someOtherGetter' rootGetters.someOtherGetter // -> 全局getter, 'someOtherGetter' } }, actions: { // 在这个模块里,dispatch和commit也被局部化了 // 他们可以接受root属性以访问跟dispatch和commit smoeActino ({dispatch, commit, getters, rootGetters }) { getters.someGetter // 'foo/someGetter' rootGetters.someGetter // 'someGetter' dispatch('someOtherAction') // 'foo/someOtherAction' dispatch('someOtherAction', null, {root: true}) // => ‘someOtherAction' commit('someMutation') // 'foo/someMutation' commit('someMutation', null, { root: true }) // someMutation } } } }
5. Binding function with namespace
As mentioned before, after bringing the namespace, the namespace must be written when calling, but this is more cumbersome, especially when it comes to When there are multiple levels of nesting (of course, don’t nest too much during development, you will get dizzy...)
Let’s look at the general writing method
computed: { ...mapState({ a: state => state.some.nested.module.a, b: state => state.some.nested.module.b }), methods: { ...mapActions([ 'some/nested/module/foo', 'some/nested/module/bar' ]) } }
In this case, you can The module's namespace is passed as the first argument to the above function, so that all bindings will automatically use the module as a context. Simplified writing is
computed: { ...mapStates('some/nested/module', { a: state => state.a, b: state => state.b }) }, methods: { ...mapActions('some/nested/module',[ 'foo', 'bar' ]) }
6. Module reuse
Sometimes we may create multiple instances of a module, for example:
Create multiple stores, They share a module
Registering the same module multiple times in a store
If we use a pure object to declare the module state, then this state object will be shared through references, causing data to contaminate each other.
In fact, the data in the Vue component has the same problem, so the solution is the same. Use a function to declare the module status (supported by 2.3.0+)
const MyModule = { state () { return { foo: 'far' } } }
7. Summary
The content of modularity (module) has been finished here. This time we mainly explain the reasons for the emergence of modules, how to use them, global and local namespaced module namespaces, local access to global content, and map functions with namespace bindings. Reuse of functions and modules.
Quote
https://vuex.vuejs.org Vuex official documentation
Related recommendations:
vuex2.0 Detailed explanation of modules instance
Detailed explanation of Vue + Vuex Detailed explanation of using vm.$nextTick instance
Learn simple vuex and modularization
The above is the detailed content of Detailed explanation of Vuex modular (module) examples. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to Optimize the Maintainability of Java Code: Experience and Advice In the software development process, writing code with good maintainability is crucial. Maintainability means that code can be easily understood, modified, and extended without causing unexpected problems or additional effort. For Java developers, how to optimize the maintainability of code is an important issue. This article will share some experiences and suggestions to help Java developers improve the maintainability of their code. Following standardized naming rules can make the code more readable.

Python, as a high-level programming language, is widely used in software development. Although Python has many advantages, a problem that many Python programmers often face is that the maintainability of the code is poor. The maintainability of Python code includes the legibility, scalability, and reusability of the code. In this article, we will focus on how to solve the problem of poor maintainability of Python code. 1. Code readability Code readability refers to the readability of the code, which is the core of code maintainability.

Python is a simple, easy-to-learn and efficient programming language, but when we write Python code, we may encounter some problems with excessive code complexity. If these problems are not solved, it will make the code difficult to maintain, error-prone, and reduce the readability and scalability of the code. So, in this article, we will discuss how to resolve code complexity error in Python code. Understanding Code Complexity Code complexity is a measure of the nature of code that is difficult to understand and maintain. In Python, there are some indicators that can be used

Vue2.x is one of the most popular front-end frameworks currently, which provides Vuex as a solution for managing global state. Using Vuex can make state management clearer and easier to maintain. The best practices of Vuex will be introduced below to help developers better use Vuex and improve code quality. 1. Use modular organization state. Vuex uses a single state tree to manage all the states of the application, extracting the state from the components, making state management clearer and easier to understand. In applications with a lot of state, modules must be used

During the development process of Python, we often encounter module not found errors. The specific manifestation of this error is that Python reports one of two errors: ModuleNotFoundError or ImportError when importing the module. This error is very annoying and can cause the program to not run properly, so in this article, we will explore the causes of this error and how to solve it. ModuleNotFoundError and ImportError in Pyth

What does Vuex do? Vue official: State management tool What is state management? State that needs to be shared among multiple components, and it is responsive, one change, all changes. For example, some globally used status information: user login status, user name, geographical location information, items in the shopping cart, etc. At this time, we need such a tool for global status management, and Vuex is such a tool. Single-page state management View–>Actions—>State view layer (view) triggers an action (action) to change the state (state) and responds back to the view layer (view) vuex (Vue3.
![How to solve the problem 'Error: [vuex] do not mutate vuex store state outside mutation handlers.' when using vuex in a Vue application?](https://img.php.cn/upload/article/000/000/164/168760467048976.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
In Vue applications, using vuex is a common state management method. However, when using vuex, we may sometimes encounter such an error message: "Error:[vuex]donotmutatevuexstorestateoutsidemutationhandlers." What does this error message mean? Why does this error message appear? How to fix this error? This article will cover this issue in detail. The error message contains

When asked in an interview about the implementation principle of vuex, how should you answer? The following article will give you an in-depth understanding of the implementation principle of vuex. I hope it will be helpful to you!
