Vuex emphasizes the use of a single state tree, that is, there is only one store in a project. This store centrally manages all the data in the project and the operations on the data. But the problem this brings is that the store may be very bloated and difficult to maintain, so the state tree needs to be split into modules.
Example tutorial
The example is built on the basis of vue-cli. The following is the content directory under the src file.
├── App.vue ├── components // 组件文件夹 │ ├── tab1.vue │ ├── tab2.vue │ ├── tab3.vue │ └── tab4.vue ├── main.js // vue的主文件入口 ├── router // vue-router文件 │ └── index.js └── store // vuex文件 ├── action.js // action ├── getter.js // getter ├── index.js // vuex的主文件 ├── module // 模块文件 │ ├── tab2.js │ └── tab3.js ├── mutation-type.js // mutation常量名文件 └── mutation.js // mutation
The effect is like this (don’t dislike the simplicity)
In this example, all the relevant knowledge of vuex mentioned in the document I have used it once, including module-related knowledge, and basically covered all general usage scenarios.
No more nonsense, let’s get started.
First of all, app.vue and router are related to routing. They are very simple things. You can understand them by looking at the documentation.
Modularization of vuex
Before writing this example, I read a lot of open source project code. It was quite fresh at first. After all, I have not used vuex in depth in previous projects. Basically, all the functions of vuex are completed in a store.js, but the project is complex and it cannot be written like this. There is a need now, so I want to write an example to clarify the ideas in this regard. The result is quite simple.
The content in the store file is built according to the five core concepts of vuex. The advantage of doing so is great convenience for sorting out business logic and later maintenance, such as mutation.js and mutation-type.js. Two files:
// mutation-type.js const CHANGE_COUNT = 'CHANGE_COUNT'; export default { CHANGE_COUNT }
// mutation.js import type from './mutation-type' let mutations = { [type.CHANGE_COUNT](state) { state.count++ } } export default mutations
Extract the method names in the mutation as constants, put them in separate files, and quote the relevant content when using them. This is very convenient for management and understanding what methods exist. It is very Intuitive. On the other hand, sometimes you may need to use action. You can use the same method name and just introduce the constant file.
// action.js import type from './mutation-type' let actions = { [type.CHANGE_COUNT]({ commit }) { commit(type.CHANGE_COUNT) } } export default actions
How about this, does it look less messy than writing it in a file?
...mapGetters and...mapActions
tab1.vue:
// tab1.vue <template> <p> </p> <p>这是tab1的内容</p> <em>{{count}}</em> <p>getter:{{NewArr}}</p> </template> <script> import { mapActions, mapGetters } from "vuex"; import type from "../store/mutation-type"; export default { computed: { ...mapGetters([ 'NewArr' ]), count: function() { return this.$store.state.count; }, }, methods: { ...mapActions({ CHANGE_COUNT: type.CHANGE_COUNT }), add: function() { this.CHANGE_COUNT(type.CHANGE_COUNT); } } }; </script> <style> </style>
index.js file:
import Vuex from 'vuex' import Vue from 'vue' import actions from './action' import mutations from './mutation' import getters from './getter' import tab2 from './module/tab2' import tab3 from './module/tab3' Vue.use(Vuex) let state = { count: 1, arr:[] } let store = new Vuex.Store({ state, getters, mutations, actions, modules:{ tab2,tab3 } }) export default store
vuex It provides something called an auxiliary function. Its advantage is that it allows you to display some things you need to use on one page, and you can also write less content when using it. However, this is not necessary. You can use it according to your needs. .
It should be noted that the places where they take effect are different.
...mapGetters are written in the calculated properties of this page, and then you can use the content in the getters just like using calculated properties.
...mapActions is written in the methods of this page. It can be called in other methods or even written directly in @click, like this:
<em>{{count}}</em>
Jiang Zi, in tab1 The number will increase by 1 each time it is clicked.
mudule
The vuex documentation is vague about the module, so you still have to use it yourself.
In this example, I set up two modules: tab2 and tab3, which correspond to two components with the same name respectively. Of course, I did this just for testing. Just look at tab2.
// module/tab2.js const tab2 = { state: { name:`这是tab2模块的内容` }, mutations:{ change2(state){ state.name = `我修改了tab2模块的内容` } }, getters:{ name(state,getters,rootState){ console.log(rootState) return state.name + ',使用getters修改' } } } export default tab2;
// tab2.vue <template> <p> </p> <p>这是tab2的内容</p> <strong>点击使用muttion修改模块tab2的内容:{{info}}</strong> <h4 id="newInfo">{{newInfo}}</h4> </template> <script> export default { mounted() { // console.log(this.$store.commit('change2')) }, computed: { info: function() { return this.$store.state.tab2.name; }, newInfo(){ return this.$store.getters.name; } }, methods: { change() { this.$store.commit('change2') } } }; </script> <style> </style>
This example mainly focuses on how to call stated in the module on the page.
First let’s talk about state. This is very simple. Just write it like this on the page:
this.$store.steta.tab2(模块名).name
Console $store in the mounted section of this page. You can see that in the module, stete has added a layer. Nested in state.
As for action, mutation, and getter, they are the same as the general usage, there is no difference.
Also, in getters and actions, the state of the root structure can be obtained through rootState. There is no such method in mutation.
Related recommendations:
Vuex improvement learning sharing
About Vuex’s family bucket status management
Implement the initialization method of vuex
The above is the detailed content of Learn simple vuex and modularization. For more information, please follow other related articles on the PHP Chinese website!

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.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

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