vuex与redux的主要区别:
redux:生成的全局数据流是通过每个组件的props逐层传递到各个子组件的,通过@connect装饰器绑定在this.props上面。
vuex :生成的全局数据则是通过getter集成到了框架内部,每个全局属性并非逐层传递到子组件,而是通过数据绑定的方式直接连接到各个子组件,数据及方法都是绑定在组件this上面。
react项目使用react-redux相关依赖;(create-react-app);
cnpm install redux react-redux redux-actions redux-thunk --save
redux-actions 用来创建规范化的action,简化reducer操作 官方api文档 https://www.npmjs.com/package/redux-actions
redux-thunk 实现redux异步操作 官方api文档 https://www.npmjs.com/package/redux-thunk
vue项目使用vuex相关依赖; (vue-cli)
cnpm install vuex --save
下面就redux 与 vuex 单个模块的state代码贴出
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完整demo 地址:https://github.com/zhuzeliang/react-node-demo
vuex完整demo 地址:https://github.com/zhuzeliang/vue-node-demo