计算属性

绑定表式虽然可以支持比较复杂的js表达式,但是在模板中写过于复杂的表达式并不利于维护,所以计算属性可以很好的来解决这个问题。

$computed方法

// es6
class App extends drunk.Component {
  init() {
    this.$computed('fullName', {
      get() {
        return this.firstName + ' ' + this.lastName;
      },
      set(fullName) {
        var arr = fullName.split(/\W+/);
        this.firstName = arr[0];
        this.lastName = arr[arr.length - 1];
      }
    });

    this.firstName = 'Todd';
    this.lastName = 'Fon';
  }
}

drunk.computed装饰器

// ts
class App extends drunk.Component {
  firstName = 'Todd';
  lastName = 'Fon';

  @drunk.computed
  get fullName() {
    return this.firstName + ' ' + this.lastName;
  }
  set fullName(fullName: string) {
    var arr = fullName.split(/\W+/);
    this.firstName = arr[0];
    this.lastName = arr[arr.length - 1];
  }
}

fullName被设置成计算属性时,firstNamelastName这两个属性都会被监听,当任何这两个属性的值改变时,fullName也会触发改变。

与$watch的区别

class App extends drunk.Component {
  firstName: string;
  lastName: string;
  fullName: string;

  init() {
    this.$watch("firstName + ' ' + lastName", (newValue: string) => {
      this.fullName = newValue;
    });
    this.$watch("fullName", (newValue: string) => {
      let arr = newValue.split(/\W+/);
      this.firstName = arr[0];
      this.lastName = arr[arr.length - 1];
    });
  }
}

通过$watch实现的方式在编码上并不直观。

results matching ""

    No results matching ""