在Angular中使用mobx

294 阅读1分钟

在Angular中使用mobx

一、mobx简介

mobx是什么

​ MobX: 简单,可扩展的状态管理。

Mobx 工作流程

img

安装使用

​ npm install mobx --save

​ npm install mobx-angular --save

二、常用 API 介绍

  1. observable

    import { observable, computed, action  } from 'mobx-angular';
    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class Store {
      // 使用装饰器 @observable  
      @observable price = 0;
      @observable amount = 0;
    }
    
    
  2. computed

    相关数据发生变化时自动更新.

    import { observable, computed, action  } from 'mobx-angular';
    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class Store {
      	// 使用装饰器 @observable  
      	@observable price = 0;
      	@observable amount = 0;
        
        
        @computed get total(): number {
        	return this.price * this.amount;
      	}
    }
    
  3. action

    修改状态

    import { observable, computed, action  } from 'mobx-angular';
    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class Store {
      @observable price = 0;
      @observable amount = 0;
      @computed get total(): number {
        return this.price * this.amount;
      }
        
        
      @action amountAction(): void {
        this.amount++;
      }
      @action priceAction(): void {
        this.price++;
      }
      @action allAction(): void {
        this.amount++;
        this.price++;
      }
    }
    
    
  4. autorun、when、reaction

    autorun:自动运行接收的参数函数

    when:接收两个函数参数,第一个函数必须根据可观察数据来返回一个布尔值,当该布尔值为 true 时,才会去执行第二个函数,并且只会执行一次。

    reaction:接收两个函数参数,第一个函数引用可观察数据,并返回一个可观察数据,作为第二个函数的参数。

    import { Component, OnInit } from '@angular/core';
    import { Store } from '../../store/counter.store';
    import { autorun, when, reaction } from 'mobx';
    
    @Component({
      selector: 'app-action',
      templateUrl: './action.component.html',
      styleUrls: ['./action.component.less']
    })
    export class ActionComponent implements OnInit {
    
      constructor(
        public store: Store
      ) {
        autorun(() => {
          console.log(store.total);
        });
    
        when(() => store.total > 100, () => {
          console.log('没钱了!');
        });
    
        reaction(() => [store.price, store.amount], arr => {
          console.log(arr);
        });
      }
    
      ngOnInit(): void {
      }
    
    }