v-if和v-for的差別:1、作用不同,v-if指令用於條件性地渲染一塊內容,這塊內容只會在指令的表達式回傳true值的時候被渲染;而v-for指令是基於一個陣列來渲染一個清單。 2.優先權不同,v-for優先權比v-if高,在進行if判斷的時候v-for是比v-if先進行判斷的。
本教學操作環境:windows7系統、vue3版,DELL G3電腦。
首先在官方文件中明確指出v-for和v-if不建議一起使用。
一、v-if和v-for的作用
v-if 指令用於條件化地渲染一塊內容。這塊內容只會在指令的表達式回傳 true值的時候被渲染。
v-for 指令是基於一個陣列來渲染一個清單。 v-for 指令需要使用 item in items
形式的特殊語法,其中 items 是來源資料數組或對象,而 item 則是被迭代的數組元素的別名。
在 v-for 的時候,建議設定key值,並且保證每個key值是獨一無二的,這方便diff演算法進行最佳化。
兩者在用法上區別如下:
<div v-if="isShow" >123</div> <li v-for="item in items" :key="item.id"> {{ item.label }} </li>
二、兩者的優先權
在使用中,v-for優先權比v-if高
v-if與v-for都是vue模板系統中的指令
在vue模板編譯的時候, 會將指令系統轉換成可執行的render函數
範例
寫一個p標籤,同時使用v-if與v-for
<div id="app"> <p v-if="isShow" v-for="item in items"> {{ item.title }} </p> </div>
建立vue實例,存放isShow與items資料
const app = new Vue({ el: "#app", data() { return { items: [ { title: "foo" }, { title: "baz" }] } }, computed: { isShow() { return this.items && this.items.length > 0 } } })
模板指令的程式碼都會產生在render函數中,透過app.$options.render就能得到渲染函數
ƒ anonymous() { with (this) { return _c('div', { attrs: { "id": "app" } }, _l((items), function (item) { return (isShow) ? _c('p', [_v("\n" + _s(item.title) + "\n")]) : _e() }), 0) } }
_l是vue的列表渲染函數,函數內部都會進行一次if判斷
初步得到結論:v-for優先權是比v-if高
然後再將v-for與v-if置於不同標籤
<div id="app"> <template v-if="isShow"> <p v-for="item in items">{{item.title}}</p> </template> </div>
再輸出下render函數
ƒ anonymous() { with(this){return _c('div',{attrs:{"id":"app"}}, [(isShow)?[_v("\n"), _l((items),function(item){return _c('p',[_v(_s(item.title))])})]:_e()],2)} }
這時候我們可以看到,v-for與v-if作用在不同標籤時候,是先進行判斷,再進行列表的渲染
我們再在查看下vue原始碼
原始碼位置:\vue-dev\src\compiler\codegen\index.js
export function genElement (el: ASTElement, state: CodegenState): string { if (el.parent) { el.pre = el.pre || el.parent.pre } if (el.staticRoot && !el.staticProcessed) { return genStatic(el, state) } else if (el.once && !el.onceProcessed) { return genOnce(el, state) } else if (el.for && !el.forProcessed) { return genFor(el, state) } else if (el.if && !el.ifProcessed) { return genIf(el, state) } else if (el.tag === 'template' && !el.slotTarget && !state.pre) { return genChildren(el, state) || 'void 0' } else if (el.tag === 'slot') { return genSlot(el, state) } else { // component or element ... }
在進行if判斷的時候,v-for是比v- if先進行判斷
最終判斷結果是v-for的優先權高於v-if的
三、注意事項
#永遠不要把v-if 和v-for 同時用在同一個元素上,帶來效能方面的浪費(每次渲染都會先循環再進行條件判斷)
如果避免這種情況,則在外層嵌套template(頁面渲染不產生dom節點),在這一層進行v-if判斷,然後在內部進行v-for迴圈
<template v-if="isShow"> <p v-for="item in items"> </template>
如果條件出現在迴圈內部,可透過計算屬性computed提前過濾掉那些不需要顯示的項目
computed: { items: function() { return this.list.filter(function (item) { return item.isShow }) } }
案例說明:
#原因:v-for比v-if優先權高,每次都需要遍歷整個數組,造成不必要的計算,影響性能.
例如,使用v-for在頁面中循環100個li標籤,但是只顯示index=97的那個li標籤內容,其餘的全部隱藏。
即使100個list中只需要使用一個數據,它也會循環整個陣列。
- {{item.name}}
解決:使用computed
<ul> <li v-for="item in activeList">{{item.name}}</li> </ul> computed: { activeList() { return this.list.filter(val => { return val.actived; }); } },
以上是vue中v-if和v-for的差別是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Include:1)AsteeplearningCurvedUetoItsVasteCosystem,2)SeochallengesWithClient-SiderEndering,3)潛在的PersperformanceissuesInsuesInlArgeApplications,4)ComplexStateStateManagementAsappsgrow和5)TheneedtokeEedtokeEedtokeEppwithitsrapideDrapidevoltolution.thereedtokeEppectortorservolution.thereedthersrapidevolution.ththesefactorsshesssheou

reactischallengingforbeginnersduetoitssteplearningcurveandparadigmshifttocoment oparchitecent.1)startwithofficialdocumentationforasolidFoundation.2)了解jsxandhowtoembedjavascriptwithinit.3)

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

javascriptfatigueinrectismanagbaiblewithstrategiesLike just just in-timelearninganning and CuratedInformationsources.1)學習whatyouneedwhenyouneedit

tateractComponents通過theusestatehook,使用jestandReaCtTestingLibraryToSigulationsimintionsandIntractions and verifyStateChangesInTheUI.1)underthecomponentAndComponentAndComponentAndConconentAndCheckInitialState.2)模擬useruseruserusertactionslikeclicksorformsorformsormissions.3)

KeysinreactarecrucialforopTimizingPerformanceByingIneFefitedListupDates.1)useKeyStoIndentifyAndTrackListelements.2)避免使用ArrayIndicesasKeystopreventperformansissues.3)ChooSestableIdentifierslikeIdentifierSlikeItem.idtomaintainAinainCommaintOnconMaintOmentStateAteanDimpperperFermerfermperfermerformperfermerformfermerformfermerformfermerment.ChosestopReventPerformissues.3)

ReactKeySareUniqueIdentifiers usedwhenrenderingListstoimprovereConciliation效率。 1)heelPreactrackChangesInListItems,2)使用StableanDuniqueIdentifiersLikeItifiersLikeItemidSisRecumended,3)避免使用ArrayIndicesaskeyindicesaskeystopreventopReventOpReventSissUseSuseSuseWithReRefers和4)

獨特的keysarecrucialinreactforoptimizingRendering和MaintainingComponentStateTegrity.1)useanaturalAlaluniqueIdentifierFromyourDataiFabable.2)ifnonaturalalientedifierexistsistsists,generateauniqueKeyniqueKeyKeyLiquekeyperaliqeyAliqueLiqueAlighatiSaliqueLiberaryLlikikeuuId.3)deversearrayIndiceSaskeyseSecialIndiceSeasseAsialIndiceAseAsialIndiceAsiall


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3漢化版
中文版,非常好用