MboX - 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;
  }
})
原文链接:segmentfault.com

上一篇:计算机基础-不懂就问
下一篇:接口管理工具YApi怎么用?颜值高、易管理、超好用

相关推荐

官方社区

扫码加入 JavaScript 社区