redux 、vuex 、 mobx区别

79 阅读3分钟

vuex

五个核心属性:state、getters、mutations、actions、modules

状态如何改变?

vuex 状态存储在state中,唯一方式是通过mutations进行改变。

如果状态是引用类型,为了避免复制后修改影响原始数据,建议深克隆复制后修改。

批量使用Vuex的state状态?

使用mapState将state放入computed中

    computed:{
        ...mapState(['test1','test2']),
    }

派生一些状态出来 如何操作

image.png

image.png

mutations

必须是同步的

    mutations:{
        setTest1(state,val){
        statÏe.test1 = val;
        }
    }
    
    在methods中调用,解构出来
    methods:{
    ...mapMutations('store1',[
    setTest1,
    ])
    }

actions

可以是异步的请求,可以返回一个promise

async dispatchTest(scope,params){
    return http.get('')
}

在methods中调用
methods:{
...mapActions('store1',[
'dispatchTest',
'dispatchTest2',

])
}

action 和mutation区别

  • mutation可以直接变更state状态,也是唯一变更state状态的方式
  • action如果想变更状态,需要提交mutation。
  • action一般用来做异步操作,而mutation只能是同步的
  • 提交方式不同,action 是用this.$store.dispatch('ACTION_NAME',data)来提交。mutation是用this.$store.commit('SET_NUMBER',10)来提交。

modules Vuex模块

  • 涉及比较大的项目,其中有全局需要用到的内容,可以放在全局的store.js中。
  • 其他的每个单独的子项目,可以放在modules中
  • 子项目如下目录 test/store.js文件
  • 全局的store可以这样写
    import test1 from test/store.js
    const store = new Vuex.Store({
    state:{},
    getters:{},
    mutations:{},
    actions:{},
    modules:{
        test1
    }
    })
    
    //////这样子 如果在子项目中调用,可以采用
    
    import {mapActions} from 'vuex';
    
    methods:{
    ...mapActions(test1,[
    ----
    ])
    }

严格模式

 struct:true;
 
 在严格模式下,如果出现了不是mutations修改状态的情况,会抛出错误,保证所有的状态变更都能被调试工具跟踪到。

image.png

mobx

创建

class Store{
        state1='test1',
        state2='test2',
        state3=[],
        constructor(){
        makeAutoObservable(this); // 使用makeAutoObservable将类实例转换为可观察对象。
        }

    async methodsTest1(){
    .....
        runInAction(()=>{
            使用runInAction批量更新state,只触发一次渲染
            this.state1 = 'test1___1';
            this.state3 = [2,3];
        
        })
    }
}
const store = new Store();
export default store;

引用

    import store from './store';
    import {observer} from 'mobx-react'
    //直接解构出来使用,更新state需要放到action中
    const page1 = (props)=>{
    
    const{
     state1,
     methodsTest1
    }=store;
    
    }
    使用observer 包裹 组件,使得组件响应式,在观察到状态发生改变后,自动更新。
    export default observer(page1);
    
    
    

区别

vuex

1. 单项数据流,只能通过 mutation更新state, 可以通过vue响应式机制进行 重新渲染。
2. 单一数据源,和redux一样,全局只能有一个store,如果想细致拆分,可以用modules 配置子模块

image.png

redux

 1. 单向数据流,发出action--reducer计算出state---subscribe监听state更新--重新渲染
 2. 单一数据源 只有一个store
 3. state只读或者说不可变 -- 每次更新之后,会返回一个新的state
 4. 支持中间件,可以管理异步数据流、增加用户信息、打点等上报

image.png

mobx

1. 响应式特性,通过observer包裹组件,makeAutoObservable将store设置为被观察对象。
   当状态发生变化,会自动追踪并触发渲染。
   更新 只能通过runInAction,如果有多个state改动,可以用runInAction包裹,只触发一次渲染
2. mobx更灵活,往往是多个store
3. mobx入侵性小,简单可扩展,容易上手。
4. 容易风格不一致,维护差一点。

redux社区和生态比较多,mobx规模较小