Angular中為什么不要在模板中調(diào)用方法_第1頁(yè)
Angular中為什么不要在模板中調(diào)用方法_第2頁(yè)
Angular中為什么不要在模板中調(diào)用方法_第3頁(yè)
全文預(yù)覽已結(jié)束

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

第Angular中為什么不要在模板中調(diào)用方法在運(yùn)行nggeneratecomponentcomponent-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

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

!--html模板--

translateName:{{originName}}

translateName:{{getTranslatedName(你好)}}

button(click)=onClick()ClickMe!/button

//組件文件

import{Component}from@angular/core

@Component({

selector:my-app,

templateUrl:./ponent.html,

styleUrls:[./ponent.css],

exportclassAppComponent{

originName=你好

getTranslatedName(name:string):string{

console.log(getTranslatedNamecalledfor,name);

returnhelloworld!

onClick(){

console.log(Buttonclicked!

}

我們?cè)谀0謇锩嬷苯诱{(diào)用了getTranslatedName方法,很方便的顯示了該方法的返回值helloworld??雌饋頉]什么問題,但如果我們?nèi)z查console會(huì)發(fā)現(xiàn)這個(gè)方法不止調(diào)用了一次。

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

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

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

一個(gè)小Demo:

/edit/angular-ivy-4bahvofile=src/app/ponent.html

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

import{Component,OnInit}from@angular/core

@Component({

selector:my-app,

templateUrl:./ponent.html,

styleUrls:[./ponent.css],

exportclassAppComponentimplementsOnInit{

originName=你好

TranslatedName:string;

ngOnInit():void{

this.TranslatedName=this.getTranslatedName(this.originName)

getTranslatedName(name:string):string{

console.count(getTranslatedName

retu

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論