微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 有角度有像vue.js中的“计算属性”功能吗?

我首先学习了Vue.js,现在在Angular 4中有一个项目,所以我刚刚学习了Angular.我发现除了“计算属性”之外,一切都与Vue没有什么不同.在Vue中,我可以创建一个计算属性来侦听其他属性的更改并自动运行计算.

例如(在Vue 2中):

computed: {
    name(){
        return this.firstname + ' ' + this.lastname;
    }
}

name属性只会在firstname或lastname之一更改时重新计算.如何在Angular 2或4中处理此问题?

解决方法:

是的你可以.

在TS文件中:

export class MyComponent {

  get name() {
     return  this.firstname + ' ' + this.lastname;
  }
}

之后在html中:

<div>{{name}}</div>

这是一个例子:

@Component({
  selector: 'my-app',
  template: `{{name}}`,
})
export class App  {
  i = 0;
  firstN;
  secondN;

  constructor() {
    setInterval(()=> {
      this.firstN = this.i++;
      this.secondN = this.i++;
    }, 2000);
  }
  get name() {
    return  this.firstN + ' ' + this.secondN;
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐