The main difference between vuex and redux:
redux: The generated global data flow is passed to each subcomponent layer by layer through the props of each component, and is bound to this.props through the @connect decorator.
vuex: The generated global data is integrated into the framework through a getter. Each global property is not passed to subcomponents layer by layer, but is directly connected to each subcomponent through data binding. Data and methods are bound in Component this above.
The react project uses react-redux related dependencies; (create-react-app);
cnpm install redux react-redux redux-actions redux-thunk --save
redux-actions is used to create standardized actions and simplify reducer operations Official api documentation https://www.npmjs.com/package/redux-actions
redux-thunk implements redux asynchronous operations official api documentation https://www.npmjs.com/package/redux-thunk
The vue project uses vuex-related dependencies; (vue-cli)
cnpm install vuex --save
The state code of a single module of redux and vuex is posted below
redux:
import { createAction, handleActions } from 'redux-actions' import { getUserInfo } from '../api/getData.js' export const saveUserInfo = createAction('SAVEUSERINFO') export const addNum = createAction('ADDNUM') export const test = handleActions({ [saveUserInfo]: (state, action) => { return { ...state, userInfo: action.payload, } }, [addNum]: (state, action) => ({ ...state,num : state.num + 1 }) }, { num: 1 , userInfo:{ user:"zq", _id:"" } }); export function getUserInfoAction() { return dispatch => { getUserInfo().then(res => { if (res.data.code === 0) { dispatch(saveUserInfo(res.data.data)) } }) } }
vuex
import { getUserInfo } from '@/api/getData' export const moduleA = { // namespaced: true, state: { userInfo: { user: "zq", _id: "" }, num: 10 }, mutations: { saveUserInfo(state, action) { state.userInfo = action }, addNum(state, action) { state.num ++ } }, getters: { num(state) { return state.num += 100 } }, actions: { async getUserInfoAction({ commit }) { try { let res = await getUserInfo() if (res.data.code === 0) { commit('saveUserInfo', res.data.data) } } catch (err) { console.log(err) } } } }
Redux complete demo address: https://github.com/zhuzeliang/react-node-demo
vuex complete demo address: https://github.com/zhuzeliang/vue-node-demo