亚洲最大看欧美片,亚洲图揄拍自拍另类图片,欧美精品v国产精品v呦,日本在线精品视频免费

  • 站長(zhǎng)資訊網(wǎng)
    最全最豐富的資訊網(wǎng)站

    Angular中為什么不要在模板中調(diào)用方法

    本篇文章給大家介紹一下Angular中不在模板(template)里面調(diào)用方法的原因,以及解決方法,希望對(duì)大家有所幫助!

    Angular中為什么不要在模板中調(diào)用方法

    在運(yùn)行 ng generate component <component-name> 命令后創(chuàng)建angular組件的時(shí)候,默認(rèn)情況下會(huì)生成四個(gè)文件:

    • 一個(gè)組件文件 <component-name>.component.ts
    • 一個(gè)模板文件 <component-name>.component.html
    • 一個(gè) CSS 文件, <component-name>.component.css
    • 測(cè)試文件 <component-name>.component.spec.ts

    【相關(guān)教程推薦:《angular教程》】

    模板,就是你的HTML代碼,需要避免在里面調(diào)用非事件類的方法。舉個(gè)例子

    <!--html 模板--> <p>   translate Name: {{ originName }} </p> <p>   translate Name: {{ getTranslatedName('你好') }} </p> <button (click)="onClick()">Click Me!</button>
    // 組件文件 import { Component } from '@angular/core';  @Component({   selector: 'my-app',   templateUrl: './app.component.html',   styleUrls: ['./app.component.css'], }) export class AppComponent {   originName = '你好';    getTranslatedName(name: string): string {     console.log('getTranslatedName called for', name);     return 'hello world!';   }    onClick() {     console.log('Button clicked!');   } }

    Angular中為什么不要在模板中調(diào)用方法

    我們?cè)谀0謇锩嬷苯诱{(diào)用了getTranslatedName方法,很方便的顯示了該方法的返回值 hello world。 看起來(lái)沒(méi)什么問(wèn)題,但如果我們?nèi)z查console會(huì)發(fā)現(xiàn)這個(gè)方法不止調(diào)用了一次。

    Angular中為什么不要在模板中調(diào)用方法

    并且在我們點(diǎn)擊按鈕的時(shí)候,即便沒(méi)想更改originName,還會(huì)繼續(xù)調(diào)用這個(gè)方法。

    Angular中為什么不要在模板中調(diào)用方法

    原因與angular的變化檢測(cè)機(jī)制有關(guān)。正常來(lái)說(shuō)我們希望,當(dāng)一個(gè)值發(fā)生改變的時(shí)候才去重新渲染對(duì)應(yīng)的模塊,但angular并沒(méi)有辦法去檢測(cè)一個(gè)函數(shù)的返回值是否發(fā)生變化,所以只能在每一次檢測(cè)變化的時(shí)候去執(zhí)行一次這個(gè)函數(shù),這也是為什么點(diǎn)擊按鈕時(shí),即便沒(méi)有對(duì)originName進(jìn)行更改卻還是執(zhí)行了getTranslatedName

    當(dāng)我們綁定的不是點(diǎn)擊事件,而是其他更容易觸發(fā)的事件,例如 mouseenter, mouseleave, mousemove等該函數(shù)可能會(huì)被無(wú)意義的調(diào)用成百上千次,這可能會(huì)帶來(lái)不小的資源浪費(fèi)而導(dǎo)致性能問(wèn)題。

    一個(gè)小Demo:

    https://stackblitz.com/edit/angular-ivy-4bahvo?file=src/app/app.component.html

    大多數(shù)情況下,我們總能找到替代方案,例如在onInit賦值

    import { Component, OnInit } from '@angular/core';  @Component({   selector: 'my-app',   templateUrl: './app.component.html',   styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit {   originName = '你好';   TranslatedName: string;    ngOnInit(): void {     this.TranslatedName = this.getTranslatedName(this.originName)   }   getTranslatedName(name: string): string {     console.count('getTranslatedName');     return 'hello world!';   }    onClick() {     console.log('Button clicked!');   } }

    或者使用pipe,避免文章過(guò)長(zhǎng),就不詳述了。

    贊(0)
    分享到: 更多 (0)
    網(wǎng)站地圖   滬ICP備18035694號(hào)-2    滬公網(wǎng)安備31011702889846號(hào)