preface

Now web applications are basically on the data-driven road, and the management of data state has naturally become the core of project development, so theoretically as long as the unified state layer, view rendering can be replaced at will frame and mode.

When we were doing projects, we mostly used VUex for VUE. React with the story. As a result, many students thought that all state management containers are bound to the page rendering framework one by one, so they suddenly wanted to experiment with redux for state management, while Vue only makes a simple page renderer

Train of thought

We know that Redux’s state is just a normal JS object that is view-aware. Redux’s entire process and Vue’s rendering driver are essentially separate. Unlike Vuex, which is an instance of vue, the state attribute is reactive. The set method of the attribute, declared in the Template, automatically collects dependencies, that is, vUE’s dual binding mode. So vuex does not need to do any operations to support VUE naturally, or vuex is a global VUE that implements the idea of Flux.

So as it says on the website, we need to do some simple binding to get Redux into vue’s data rendering mode,

However, this website is no longer valid…  ̄□ ̄ | |

However, redux also has a common UI-driven solution on its website

The idea is to update the UI layer in a callback after our Dispatch action. However, $forceUpdate on vUE every time state changes would be too rigid and wasteful of performance.

React-redux takes over the parameters required by the current component from the state of redux to the functions of the React component, allowing the component data to drive UI updates.

In addition, vue’s own data is reactive, so you only need to inject the state in REdux into vue’s data, and then modify the data according to the state in the SUBSCRIBE callback of REdux to drive VUE to render the page smoothly. So you just need to inject state into the data before the VUE component is mounted. For VUe2, we can only use mixins to mix data into components, but for VUe3 we can use composition Component to inject data into setup

Example Description: Do a simple little function test, click the sider page TAB to send the page name to state, and then drive the header page update.

Effect:

Steps:

1 Build the Redux Store

import { createSlice, PayloadAction } from '@reduxjs/toolkit'
export interface GlobalState {
    currentRoute: string,
}
// Initialize state
const initialState: GlobalState ={
    currentRoute: 'Application Management',}export const globalSlice = createSlice({
  name: 'global',
  initialState,
  reducers: {
    updata: (state, action: PayloadAction<string>) = > {
      state.currentRoute = action.payload
    },
  },
})

// Action creators are generated for each case reducer function
export const { updata } = globalSlice.actions

export default globalSlice.reducer




import { configureStore } from '@reduxjs/toolkit'
import global from './reducers/globalSlice'
export const store = configureStore({
    reducer: {
        global:global
    },
  })
  store.subscribe(() = >{
      console.log('subscribe')})Copy the code

The generated state, and the corresponding action

2. Establish reduxConnect, the connection component between REDUx and VUE

import {  reactive,onMounted } from 'vue';
import { store } from '.. /config/store/store.ts';
/* mapStateToData: State description set. Example :[{global:['currentRoute']}] */
export default (mapStateToData:Array<any>)=>{
    interface ObjType {
        [propName: string]: any;
    }
    const state:ObjType = reactive({}) 
    // Generate vue data with redux state
    const generate = () = >{
        if(! mapStateToData.length)return
        const _state = store.getState() 
        for(const map of mapStateToData){
            const k = Object.keys(map)[0]
            const module = map[k]
            for(const v of module) {// Shallow comparison substitution
                if(! state[v]||state[v]! =_state[k][v])state[v] = _state[k][v] } } } generate() onMounted(() = >{
        // Update the vue Data driver page update in the state completed update callback
        store.subscribe((v:any) = >{
            generate()
        })
    })
    return {state}
}
Copy the code

3 Connect vUE and Redux based on state description rules in the header component

   setup(props){
        return{... reduxConnect([{global: ['currentRoute']}}}]),Copy the code

At this point, state is injected into the VUE component (it would be more accurate to generate a new Vue data attribute based on state).4 Update state in the SIDER component with dispatch Action and drive page update

this.store.dispatch(updata(params.label))
Copy the code

Postscript this time a small experiment is mainly to verify some of their own small conjecture, by the way to consolidate the relevant knowledge and understanding. Both Vuex and Redux are excellent frameworks. There are many different uses for state containers. Some students never need to manage only the state within the component itself, some globally hang an object for management, and some entrust all the state to the container for management. You can’t say who is right and who is wrong. Project environments are so different that there is no best use, only the most appropriate use