MboX-Computed

59次阅读

共计 795 个字符,预计需要花费 2 分钟才能阅读完成。

一:标记变量为 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;}
})

正文完
 0