我先学了 Vue.js,现在有一个 Angular 4 的项目,所以我才学了 Angular。我发现除了“计算属性”之外,一切都与 Vue 没有什么不同。在 Vue 中,我可以创建一个计算属性来监听其他属性的变化并自动运行计算。
例如(在 Vue 2 中):
computed: {
name(){
return this.firstname + ' ' + this.lastname;
}
}
name 属性只会在 firstname 或 lastname 之一发生变化时重新计算。如何在 Angular 2 或 4 中处理这个问题?
最佳答案
虽然这已经得到回答,但我认为这不是很好的答案,用户不应该使用 getter 作为 Angular 计算属性。为什么你会问? getter 只是函数的糖语法,它将被编译为普通函数,这意味着它将在每次更改检测检查时执行。这对性能来说很糟糕,因为任何更改都会重新计算属性数百次。
看看这个例子:https://plnkr.co/edit/TQMQFb?p=preview
@Component({
selector: 'cities-page',
template: `
<label>Angular computed properties are bad</label>
<ng-select [items]="cities"
bindLabel="name"
bindValue="id"
placeholder="Select city"
[(ngModel)]="selectedCityId">
</ng-select>
<p *ngIf="hasSelectedCity">
Selected city ID: {{selectedCityId}}
</p>
<p><b>hasSelectedCity</b> is recomputed <b [ngStyle]="{'font-size': calls + 'px'}">{{calls}}</b> times</p>
`
})
export class CitiesPageComponent {
cities: NgOption[] = [
{id: 1, name: 'Vilnius'},
{id: 2, name: 'Kaunas'},
{id: 3, name: 'Pabradė'}
];
selectedCityId: any;
calls = 0;
get hasSelectedCity() {
console.log('hasSelectedCity is called', this.calls);
this.calls++;
return !!this.selectedCityId;
}
}
如果你真的想要计算属性,你可以使用像 mobx 这样的状态容器
class TodoList {
@observable todos = [];
@computed get unfinishedTodoCount() {
return this.todos.filter(todo => !todo.finished).length;
}
}
mobx 有 @computed 装饰器,所以 getter 属性将被缓存并仅在需要时重新计算
关于javascript - angular 是否具有 vue.js 中的 "computed property"功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43710642/