计算属性

           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;
    }
}

mobx源码解读3

相关文章:

  • 2022-12-23
  • 2021-10-07
  • 2022-01-04
  • 2020-03-30
  • 2021-05-22
  • 2022-12-23
  • 2021-08-05
  • 2021-11-30
猜你喜欢
  • 2021-09-28
  • 2021-05-22
  • 2021-07-31
  • 2021-06-16
  • 2022-12-23
  • 2021-06-30
  • 2021-06-13
相关资源
相似解决方案