A detailed explanation of modular organization in Vuex
This article mainly introduces the detailed explanation of Vuex's advanced modular organization. Now I share it with you and give it as a reference.
Homemade vuex LOGO
The first two articles explained the basic usage of Vuex, but it is definitely unreasonable to write like this in actual projects. If There are too many components, and it is impossible to put all component data in one store.js, so Vuex needs to be organized in a modular manner. First, take a look at the project structure.
Project structure
1. First execute the following command:
vue init webpack-simple vuex-demo cd vuex-demo npm install npm install vuex -S npm run dev
2. Follow the above Graph structure creation file directory
Vuex modular directory
3. Write files
We Just use the examples from the previous two articles. Let’s first talk about the role of each file
Define constants in types.js, use constants to replace mutation event types
User.js Write the state, getters, actions and used in the user component mutations, and finally export them uniformly (similar to store.js in the previous example)
Write the original getters in getters.js to obtain attributes
Write the original actions in actions.js , which are the actions to be executed, such as process judgment and asynchronous requests
index.js is used to assemble actions.js, getters.js, and user.js, and then export them uniformly
1. Import the index.js file in main.js and register it
import Vue from 'vue' import App from './App.vue' import store from './store/index.js' new Vue({ store, el: '#app', render: h => h(App) })
2. Define constants in types.js and export them, all capital letters by default
// 定义类型常量,默认全部大写 const INCREMENT = 'INCREMENT' const DECREMENT = 'DECREMENT' export default { INCREMENT, DECREMENT }
Note: Placing these constants in separate files allows your code collaborators to see at a glance the mutations contained in the entire app. It's up to you whether to use constants or not - this can be helpful in large projects where multiple people are working together. But if you don't like it, you don't have to do it.
3. Write the state, getters, actions and mutations used in the user component in user.js
// 导入 types.js 文件 import types from "./../types"; const state ={ count:5 } // 定义 getters var getters ={ count(state){ return state.count } } const actions ={ increment({ commit, state }){ // 此处提交的事件与下方 mutations 中的 types.INCREMENT 对应,与原来 commit('increment') 的原理相同,只是把类型名换成了常量 commit(types.INCREMENT) }, decrement({commit,state}){ if (state.count>10) { // 此处提交的事件与下方 mutations 中的 types.DECREMENT 对应 commit(types.DECREMENT) } } } const mutations ={ // 此处的事件为上方 actions 中的 commit(types.INCREMENT) [types.INCREMENT](state){ state.count++ }, // 此处的事件为上方 actions 中的 commit(types.DECREMENT) [types.DECREMENT](state){ state.count-- } } // 最后统一导出 export default { state, getters, actions, mutations }
Note: [types.INCREMENT in the mutations above ] writing method, because types.INCREMENT is an object, it cannot be written directly as a function name. You need to use the ES2015 style calculated property naming function to use a constant as the function name before it can be used normally. The original writing method is:
const mutations ={ increment(state){ state.count ++; } }
4. Write the original method of determining odd and even numbers in getters.js
// 因为数据从 user.js 中获取,所以需要引入该文件 import user from './modules/user' const getters = { isEvenOrOdd(state){ // 注意数据是从 user.js 中获取的,所以写成 user.state.count return user.state.count % 2 == 0 ? "偶数" : "奇数" } } // 并导出 export default getters;
5. Write the original asynchronous operation in actions.js
// 异步操作中需要用到 increment 方法,所以需要导入 types.js 文件 import types from './types' const actions= { incrementAsync({ commit, state }) { // 异步操作 var p = new Promise((resolve, reject) => { setTimeout(() => { resolve() }, 3000); }); p.then(() => { commit(types.INCREMENT); }).catch(() => { console.log('异步操作'); }) } } // 最后导出 export default actions;
6. Assemble actions.js, getters.js, and user.js in index.js, and then export them uniformly
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) import getters from './getters' import actions from './actions' import users from './modules/user' // 导出 store 对象 export default new Vuex.Store({ getters, actions, modules:{ users } })
Note: When exporting the store object , because getters and actions have default values in the core concepts of vuex and can be written directly. But users is not the default, so the modules object in vuex is used for export
Core concepts
7. The Vue.app file does not make any Modification
<template> <p id="app"> <button @click="increment">增加</button> <button @click="decrement">减少</button> <button @click="incrementAsync">延时增加</button> <p>{{count}}</p> <p>{{isEvenOrOdd}}</p> </p> </template> <script> import { mapGetters, mapActions } from "vuex"; export default { name: 'app', data () { return { msg: 'Welcome to Your Vue.js App' } }, computed:mapGetters([ 'count', 'isEvenOrOdd' ]), methods:mapActions([ 'increment', 'decrement', 'incrementAsync' ]) } </script>
Finally, the thrilling time has come, whether the thing I have spent so much effort on can run
vuex modular.gif
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
AngularJS two-way data binding principle (detailed tutorial)
Related data storage and value acquisition in WeChat applet Question
How to implement the streamlined style in Vue (detailed tutorial)
How to customize the global component in vue?
The above is the detailed content of A detailed explanation of modular organization in Vuex. 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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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 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

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.
![How to solve the problem 'Error: [vuex] unknown action type: xxx' when using vuex in a Vue application?](https://img.php.cn/upload/article/000/887/227/168766615217161.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
In Vue.js projects, vuex is a very useful state management tool. It helps us share state among multiple components and provides a reliable way to manage state changes. But when using vuex, sometimes you will encounter the error "Error:[vuex]unknownactiontype:xxx". This article will explain the cause and solution of this error. 1. Cause of the error When using vuex, we need to define some actions and mu

How to achieve reasonable splitting and modular organization of requests in FastAPI Introduction: FastAPI is a high-performance web framework based on Python. It provides asynchronous support and automated API document generation, so when developing large projects, we need to consider how to Reasonably split and modularize requests. This article will introduce a method to achieve reasonable splitting and modular organization of requests in FastAPI, and give corresponding code examples. 1. Why do we need reasonable splitting and modular organization of requests?
![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

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

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.
