🎉 Vue to build large single-page e-commerce applications open source! Click me to see the source 🚀🚀
It will take you about 8 minutes to read this article. Please like 👍
What is Vuex?
Vuex is used to manage the state of all components of a Vue, which is, in plain English, an advanced way of communicating between components.
Vuex official document has been explained in great detail, so it is recommended to read it thoroughly. This paper is a summary of my own learning, practice and conclusion, and some concepts and sentences are borrowed from the official.
Why Vuex?
The common ways to communicate with components are props,$emit/ V-ON, and $parent / $children & $refs these three, and their limitation is that only in parent-child communication in the components, not in the office of the brothers components in communication, the other two are the central Bus, Bus publish-subscribe pattern can be in any communication between components, but if in a large project will inevitably have some bottlenecks, high coupling between components, then Vuex is proper, The ability to properly manage state in components (communication, method capture implementation, data transfer), separate state from components, define and isolate concepts in state management, and enforce rules to maintain the independence of views and states makes our code more structured and maintainable.
Vuex core
Vuex provides a singleton Store, which is like a container, containing the public data of the states in your application. We use the singleton Store to manage these states dynamically and uniformly according to the established rules, which is the core of Vuex.
1.State
State is a pure object with some state mounted on it, and an app should only have one state in store.js
exportDefault new vuex. Store({state: {// initial state name:'geek James', height: 180, age:27}})Copy the code
1.1mapState
:
Use the mapState helper function to generate computed properties, introduce the helper function with import {mapState} from ‘vuex’ in components that need to communicate, and then map the data in computed properties computed hooks.
mapState
Auxiliary functions can be used in three ways:
- The first is to evaluate the property by taking the return value from the arrow function
computed:mapStates({
name:state=>state.name,
height:state=>state.name,
age:state=>state.age
})
Copy the code
- Second method: using ES6… Extended features (recommended)
computed:{ ... mapState(['name'.'height'.'age'])}Copy the code
- Third method: using ES6… Extension properties are evaluated by objects
computed:{ ... mapState({ name:state=>state.name, height:state=>state.height, age:state=>state.age }) }Copy the code
Fetch data from the component
<template>
<div class="app"Height :{{height}}</div> </div> </div> </div> </template>Copy the code
Output result:
2.Getter
Think of it as a computed property of a store. Just like a computed property, the return value of a getter is cached based on its dependency and is recalculated only if its dependency value changes.
2.1mapGetter
MapGetter is an auxiliary function of the getter. Use the same method as mapState. Extension is recommended. To value.
3.Mutation
Mutations in Vuex are very similar to events: each mutation has a string event type (type) and a callback function (handler). This callback is where we actually make the state change, and it accepts state as the first argument, the only way to change state synchronously.
Synchronous change
store
state
commit
mutation
methods: {
add () {
Store.commit('increment', { number: 10 });
},
reduce () {
Store.commit('reduce'); }}Copy the code
Another way to write it: object style submission
Constants are recommended instead of Mutation event types
Remember in component communication that publish-subscribe methods communicate between components, using constants to define event types? This method is also highly recommended in Vuex. Consolidate the mutation event constants into a folder called mutation-type.js and export them.
The mutation -type. Js
export const ADD = 'ADD'
export const REDUCE = 'REDUCE'
Copy the code
Import {ADD,REDUCE} from ‘./mutation-type.js’ in store.js
import {ADD,REDUCE} from './mutation-type.js'mutation:{ [ADD](state,payload) { state.age += payload.number; }, [REDUCE](state,payload) { state.age --; }}Copy the code
Similarly, import {ADD,REDUCE} from ‘./mutation-type.js’ in required components
3.1 mapMutation
MapMutation is an auxiliary function of mutation, similar to state. Extend the operation to evaluate directly.
4.Action
- Action submits
mutation
, rather than directly changing the state. - Actions can contain any asynchronous operation.
Register a simple Action and pass in values from outside.
store.dispatch
Another way to write it: parameter deconstruction
add({commit}) {
commit('add');
}
Copy the code
4.1 mapAction
MapAction is an auxiliary function to the action, which makes it easy to call the events in the action from the Vue component. In the Vue component, the mapping can be done by deconstructing the mapAction
methods: { ... mapActions(['add'."reduce"])}Copy the code
At the same time, at the same timemapActiono
If you need to pass parameters after mapping methods, you need to write them where the event is triggered
<button @click="add({number:10})"> Add age </button>Copy the code
4.2 combination Action
Combining an Action is a way of asynchronously processing multiple COMMIT events. You can transfer the Action to each other and guarantee the stability and orderliness of the data state with the help of promises.
Official example:
In the store. In js
store.dispatch('actionA').then(() => {
})
Copy the code
In another action you can commit events asynchronously:
actions: {
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
commit('someOtherMutation')}}}Copy the code
Recommended reading:
MDN Promise
async / await
5.Module
When the application becomes very complex, the Store object can become quite bloated. To solve this problem, we can split the five states in the Store into a single model and introduce them through a portal. Typically during project development, create a store directory in the SRC directory and create the following files
Import all files in index.js and mount them uniformly on the Vuex instance
main.js
index.js
Common project structure:
├─ index.html ├─ download.js ├─ API │ ├─ ├─ ├─Extract THE API request├ ─ ─ components │ ├ ─ ─ App. Vue │ └ ─ ─... └ ─ ─ store ├ ─ ─ index. Js# where we assemble modules and export store├ ─ ─ state. Js# rootlevel state├ ─ ─ actions. JsRoot level action├ ─ ─ getter. JsRootlevel getters├ ─ ─ mutations. JsMutation at the root level├ ─ ─ mutations -type. Js# mutation Event constant name└ ─ ─ modules ├ ─ ─ a. s# a module└ ─ ─ b.j s# b module└ ─ ─...Copy the code
Scan the following TWO-DIMENSIONAL code, reply learning can be free to receive the latest front-end learning materials, but also hope that in the way of front-end advancement, we grow together, progress together!