Vue:计算属性computed的set

13,594 阅读1分钟

计算属性(computed)很简单,而且也会大量使用,但大多数时候,我们只是用它默认的 get 方法,也就是平时的常规写法,通过 computed 获取一个依赖其它状态的数据。比如:

computed: {
  fullName () {
    return `${this.firstName} ${this.lastName}`;
  }
}

这里的 fullName 事实上可以写为一个 Object,而非 Function,只是 Function 形式是我们默认使用它的 get 方法,当写为 Object 时,还能使用它的 set 方法:

computed: {
  fullName: {
    get () {
      return `${this.firstName} ${this.lastName}`;
    },
    set (val) {
      const names = val.split(' ');
      this.firstName = names[0];
      this.lastName = names[names.length - 1];
    }
  }
}

计算属性大多时候只是读取用,使用了 set 后,就可以写入了,比如上面的示例,如果执行 this.fullName = 'Aresn Liang',computed 的 set 就会调用,firstName 和 lastName 会被赋值为 Aresn 和 Liang。