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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software