搜尋
首頁web前端前端問答vue中v-if和v-for的差別是什麼

vue中v-if和v-for的差別是什麼

Dec 27, 2022 pm 06:48 PM
vue3v-ifv-for

v-if和v-for的差別:1、作用不同,v-if指令用於條件性地渲染一塊內容,這塊內容只會在指令的表達式回傳true值的時候被渲染;而v-for指令是基於一個陣列來渲染一個清單。 2.優先權不同,v-for優先權比v-if高,在進行if判斷的時候v-for是比v-if先進行判斷的。

vue中v-if和v-for的差別是什麼

本教學操作環境: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(&#39;div&#39;, { attrs: { "id": "app" } }, 
  _l((items), function (item) { return (isShow) ? _c(&#39;p&#39;, [_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(&#39;div&#39;,{attrs:{"id":"app"}},
  [(isShow)?[_v("\n"),
  _l((items),function(item){return _c(&#39;p&#39;,[_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 === &#39;template&#39; && !el.slotTarget && !state.pre) {
  return genChildren(el, state) || &#39;void 0&#39;
 } else if (el.tag === &#39;slot&#39;) {
  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;
    });
  }
},

【相關推薦:vuejs影片教學web前端開發

以上是vue中v-if和v-for的差別是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
反應的局限性是什麼?反應的局限性是什麼?May 02, 2025 am 12:26 AM

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

React的學習曲線:新開發人員的挑戰React的學習曲線:新開發人員的挑戰May 02, 2025 am 12:24 AM

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

為React中的動態列表生成穩定且獨特的鍵為React中的動態列表生成穩定且獨特的鍵May 02, 2025 am 12:22 AM

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

JavaScript疲勞:與React及其工具保持最新JavaScript疲勞:與React及其工具保持最新May 02, 2025 am 12:19 AM

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

使用USESTATE()掛鉤的測試組件使用USESTATE()掛鉤的測試組件May 02, 2025 am 12:13 AM

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

React中的鑰匙:深入研究性能優化技術React中的鑰匙:深入研究性能優化技術May 01, 2025 am 12:25 AM

KeysinreactarecrucialforopTimizingPerformanceByingIneFefitedListupDates.1)useKeyStoIndentifyAndTrackListelements.2)避免使用ArrayIndi​​cesasKeystopreventperformansissues.3)ChooSestableIdentifierslikeIdentifierSlikeItem.idtomaintainAinainCommaintOnconMaintOmentStateAteanDimpperperFermerfermperfermerformperfermerformfermerformfermerformfermerment.ChosestopReventPerformissues.3)

反應中的鍵是什麼?反應中的鍵是什麼?May 01, 2025 am 12:25 AM

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

反應中獨特鍵的重要性:避免常見的陷阱反應中獨特鍵的重要性:避免常見的陷阱May 01, 2025 am 12:19 AM

獨特的keysarecrucialinreactforoptimizingRendering和MaintainingComponentStateTegrity.1)useanaturalAlaluniqueIdentifierFromyourDataiFabable.2)ifnonaturalalientedifierexistsistsists,generateauniqueKeyniqueKeyKeyLiquekeyperaliqeyAliqueLiqueAlighatiSaliqueLiberaryLlikikeuuId.3)deversearrayIndi​​ceSaskeyseSecialIndiceSeasseAsialIndiceAseAsialIndiceAsiall

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 英文版

SublimeText3 英文版

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

MantisBT

MantisBT

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

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用