一:标记变量为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;
}
})
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。