计算属性
function Todo() {
this.id = Math.random()
mobx.extendObservable(this, {
aaa: 222,
bbb: 11,
ccc: function(){
return this.aaa + this.bbb
}
})
}
var vm = new Todo
mobx.autorun(function () {
console.log(vm.ccc)
})
这种方式 已经被废掉
要求使用修饰符或修饰方法
function Todo() {
this.id = Math.random()
mobx.extendObservable(this, {
aaa: 222,
bbb: 11,
ccc: mobx.computed(function(){
return this.aaa + this.bbb
},this)
})
}
var vm = new Todo
mobx.autorun(function () {
console.log(vm.ccc)
})
也可以使用IE8发明的get关键字,相实就是相当于把this绑定好,转换为访问器属性
function Todo() {
this.id = Math.random()
mobx.extendObservable(this, {
aaa: 222,
bbb: 11,
get ccc(){
return this.aaa + this.bbb
}
})
}
var vm = new Todo
mobx.autorun(function () {
console.log(vm.ccc)
})
更酷的是这个:
import {observable, computed} from "mobx";
class OrderLine {
@observable price:number = 0;
@observable amount:number = 1;
constructor(price) {
this.price = price;
}
@computed get total() {
return this.price * this.amount;
}
}