1. What is vuex
Vuex is designed for Vue The state management mode of JS application development adopts centralized storage to manage the state of all components of the application and solve the multi-component data communication
Generally speaking, vuex is an official tool provided by vue that is independent of the component system and manages public data
In vue2, we usually use the method of transferring data from parent to child and from child to parent. In this way, we can do some small projects. When the project is large, it will be very troublesome to write in this way. At this time, we can use vuex's plug-in to put the data into a container that can be used by both parent and child components
vue's Five Dragon subduing palms
- state: unified definition of public data (similar to data(){return {a:1, b:2, xxxxx})
- mutations: use it to modify data (similar to methods)
- getters: similar to computed (calculate attributes, calculate the existing state to get new data ------ derivation)
- actions: initiate asynchronous requests
- modules: module splitting
We need to make some preparations before we practice this martial arts
Configuration item preparation
Overall steps:
- Installation. It is a separate package and needs to be installed first.
- to configure
a. Create vuex Store instance
b. Inject store into Vue instance - use. Using store in components
1. Installation package
Enter the project directory and install the package
npm install vuex@3.6.2
Development dependency: NPM I xxxx -- save dev; npm i xxxx -D ;
Production dependency: NPM I xxxx -- save; npm i xxxx -S; npm i xxxx
2. Create a folder
The operation of routing is basically the same. Create a folder
Root component └── src ├── main.js ├── router │ └── index.js # route └── store └── index.js # vuex
In store / index JS, as follows:
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state(){ return { // It is public data, and all components can be used directly count: 100 } } }) export default store
3. Inject store into Vue instance
In Src / main JS:
- Import store
- And inject Vue instances
// Omit others // 1. Import store import store from './store' new Vue({ // Omit other store // 2. Inject Vue instance })
Using store in components
In any component, through this$ store. State to get public data
First palm!!! (state)
He is directly in the configuration file index JS const store = new vuex Store operation
The role of state is the same as that of data in the component. Both are used to access data
new Vuex.store({ state() { return { Attribute name: attribute value } } })
usage method:
- In the component, through this$ store. state. Property name to access
- If you access the template string directly, you can omit this and write it directly as: {{$store.state. Attribute name}}
Second palm!!! (modify public data with mutations)
The function is to modify the public data defined in state by calling changes.
It is similar to the methods The usage of is the same, which is to modify the data
There are two formats: definition format and call format
Define format:
new Vue.store({ // Omit other mutations: { // Each item is a function that can declare two formal parameters mutation Name 1: function(state , data) { }, mutation First name 2: function(state , data) { } } })
● the first parameter is required and indicates the current state. No need to pass in when using
● the second parameter is optional, which indicates the load and is optional. Data to be passed in when using
Call format:
this.$store.commit('mutation name', Argument)
The operation flow chart is as follows:
The schematic diagram is as follows:
Third palm!!! Derived state
Function: Based on the data in state, further process the data to get new data. (same as calculated in the component)
Define format
new Vuex.store({ // Omit other getters: { // State is the public data state defined above getter Your name 1: function(state) { return Value to return } } })
State is the public data state defined above
Use format
In the component through: $store getters. The name of getter
Summary of the first three Palms:
Fourth palm!!! (vuex actions - send asynchronous requests)
actions introduction
● actions is a configuration item of vuex
● function: send asynchronous request to obtain data, call mutations to save data, and encapsulate the whole ajax operation into Vuex
● key points:
○ asynchronous request operation can be sent inside the action
○ action modifies the state indirectly: it modifies the state by calling mutation
Define format:
new Vuex.store({ // Omit other actions: { // The context object is automatically passed in, which has the same methods and properties as the store instance action Name of: function(context, load) { // 1. Send asynchronous request to request data // 2. commit calls mutation to modify data // context.commit('mutation name ', load) } } })
Call format
In the component through this$ store. Dispatch ('name of actions', parameter) to call action
Examples
Write the action in the book request in the above example
// Send an ajax request, get the data from the back end, and then modify the data in the state actions: { getBooks (context) { // 1. Send asynchronous request axios({ url: 'https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books', method: 'GET' }).then(res => { console.log(res) // 2. Call mutation context.commit('setBooks', res.data.data) }) } },
Fifth palm!!! (use modules to split complex business)
The fifth palm is the collection of the first four palms
The function of modules: split modules to separate complex scenes according to modules
format
export default new Vuex.Store({ // state: used to save all public data state: {}, getters: {}, mutations: {}, actions: {}, modules: { Module name 1: { // If named is true, the module name must be added when using mutations namespaced: true, state: {}, getters: {}, mutations: {}, actions: {}, modules: {} }, Module name 2: { // Namemapped is not written, and the default is false. When using mutations, you do not need to add a module name state: {}, getters: {}, mutations: {}, actions: {}, modules: {} } } })
You can also further split the file.
|--store / |------- index.js # Introduction module |------- modules |-------------- / mod1.js # Module 1 |-------------- / mod2.js # Module 2
Call the state, mutation, getters and actions methods in the module
getters : this.$store.getters ['module 1/g name']
state: this.$store.state. Module 1 Data name
mutation: this.$store.commit('module 1/m name, parameter)
action: this.$store.dispatch('module 1/a name ', parameter)
Summary schematic