Vuex and REdux are state management libraries that manage state separately. Of these, Redux is a generic library that can be used on its own. Vuex is specifically designed to work with VUE. They both apply the idea of the Flux architecture, but differ slightly in the interface provision.

redux

The redux library first introduces the following concepts

  1. state
  2. reducer
  3. action
  4. dispatch

The role of State is to store data state, the role of Reducer is to modify the state according to instructions, the role of Acticon is to describe how to modify the state at a certain time, and the role of Dispatch is to drive the state to modify.

An API is provided in Redux to implement these functions. Sample code is as follows:

import {createStore} from 'redux'
// Create an instance of the Store class and pass it to reducer
const store = createStore(reducer);
Reducer is a function that receives the current state and actions and modifies the state according to the instructions of the actions
The return value from the reducer is the latest state
function reducer(state, action){
	// Change state based on the value of type in action and return
}
// Check the current status
store.getState()
// The driver status changed
let action = {type: 'ADD'.step: 1}
store.dispatch(action);
Copy the code

Of course, asynchronous action is also introduced in Redux

More often than not, our state changes are combined with asynchronous requests. Of course, we can modify the state after the asynchronous request succeeds, for example

fetch('xxxxx').then(res= > res.json).then(data= > {
	store.dispatch({type:'INIT', data})
})
Copy the code

Such an approach can be combined with asynchronous requests through state management libraries, but the combination is poor.

So, we were better off using middleware provided by Redux itself. In the middle of redux, actions can be processed by each middleware in turn, and then returned to the next middleware for further processing. Each middleware has its own circuit breaker mechanism (calling next(Actioin) can decide whether or not to be processed by the next middleware). The default dispatch can be considered the default middleware (which has the ability to trigger a reducer). However, Redux’s middleware pattern adopts a Creodized API style, and what we end up with is a modification of the original Dispatch method to make Dispatch more functional.

Each layer of middleware has a fixed interface. Here is a code example:

import {createStore, applyMiddleware} from 'redux'

// Create a redux middleware that can make the dispatch receiver function
function createMiddle(){
	// This function is returned as middleware, where
    // Store represents a repository instance, which can get state, dispatch, etc
    // Next represents the actual dispatch
    // Action represents the action returned by the previous middleware
	return store= > next= > action= > {
    	if(typeof action === 'function'){
        	action(next)
        }else{
        	next(action)
        }
    }
}

const store = createStore(reducer, appliMiddleware(createMiddle()));
// When triggered
let action = dispatch= > {
	fetch('xxx').then(response= > response.json()).then(data= > {
    	dispatch({type: 'ADD', data});
    })
}
store.dispatch(action);
Copy the code

vuex

Vuex is a library specially designed to cooperate with VUejS for state management. It combines the characteristics of VUE data response, and also introduces several concepts in VUex.

  1. state
  2. getters
  3. mutations
  4. actions

Vuex manages state like this: State stores state, and getters is a derivative of state. Mutations are handed over to handle the changes in the state, and we can directly drive mutations from the view to make the state change. Actions is used to deal with asynchrony, but of course mutations can also be driven in Actions to change the state.

The code is as follows:

import Vuex from 'vuex'
import Vue from 'vue'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
    	sex: true // Indicates gender
    },
    getters: {
    	showSex(state){
        	return state.sex ? 'male' : 'woman' // Derive the displayed result from the state in}},mutations: {
    	setSex(state, payload){
        	state.sex = payload.sex // Change the value of sex according to the load}},actions: {
    	getSexState(store){
        	fetch('xxx').then(response= > response.json()).then(data= > {
            	store.commit('setSex', {sex: data.sex});
            })
        }
    }
})

store.commit('setSex', {sex: false}); // Change the status
store.dispatch('getSexState'); // Modify the state based on the result of the asynchronous request
Copy the code