MobX - Computed

一:标记变量为computed的4种方式

1:使用@computed

import { observable, computed } from "mobx"
class OrderLine {
  @observable price = 0;
  @observable amount = 1;
  constructor(price){
    this.price = price;
  }
  @computed get total(){
    return this.price * this.amount;
  }
}

2: 使用computed

import {observable, computed} from 'mobx'

let numbers = observable([1, 2, 3])
let sum = computed(()=>numbers.reduce((a, b)=>a + b, 0))

3: 使用decorate

import { observable, computed, decorate } from "mobx"
class OrderLine {
  price = 0;
  amount = 1;
  constructor(price){
    this.price = price;
  }
  get total(){
    return this.price * this.amount;
  }
}
decorate(OrderLine, {
  price: observable,
  amount: observable,
  total: computed
});

4:默认是computed的情况
observable.object和extendObservable会自动把getter属性标记为computed:

import { observable, computed, decorate } from "mobx"
const OrderLine = observable.object({
  price: 0,
  amount: 1,
  get total(){
    return this.price * this.amount;
  }
})
阅读 266

推荐阅读
前端
用户专栏

主要是前端的一些东西

10 人关注
79 篇文章
专栏主页