v-for 基本用法
v-for?是 Vue 中用于循環渲染列表的指令,基本語法如下:
運行
<!-- Vue2 和 Vue3 通用基本語法 -->
<div v-for="(item, index) in items" :key="item.id">{{ index }} - {{ item.name }}
</div>Vue2 和 Vue3 的主要區別
1. key 屬性的必要性
Vue2:
key?屬性在?v-for?中強烈建議使用,但不是強制要求Vue3:當使用?
<template v-for>?時,key?應該放在實際的元素上而不是?<template>?標簽上
2. v-for 與 v-if 的優先級
Vue2:
v-for?優先級高于?v-if,不推薦在同一元素上同時使用Vue3:
v-if?優先級高于?v-for,在同一元素上同時使用會導致錯誤
運行
<!-- Vue2 中不推薦的做法,Vue3 中會報錯 -->
<div v-for="item in items" v-if="item.isActive" :key="item.id">{{ item.name }}
</div><!-- 推薦做法:使用計算屬性過濾或在外層使用 template -->
<template v-for="item in activeItems" :key="item.id"><div>{{ item.name }}</div>
</template>3. 數組變化檢測
Vue2:使用以下數組方法會觸發視圖更新:
push(),?pop(),?shift(),?unshift(),?splice(),?sort(),?reverse()Vue3:同樣支持這些方法,但由于 Vue3 使用 Proxy 實現響應式,直接通過索引修改數組也會觸發更新
// Vue2 中不會觸發更新
this.items[0] = newValue// Vue2 中需要這樣寫
this.$set(this.items, 0, newValue)// Vue3 中直接賦值即可
this.items[0] = newValue // 會觸發更新4. 對象迭代變化
Vue2:
v-for?遍歷對象時順序基于?Object.keys()?的枚舉順序Vue3:保持 Vue2 的行為,但新增了遍歷范圍的概念
運行
<!-- Vue3 新增的 range 用法 -->
<div v-for="n in 10" :key="n">{{ n }}</div>5. 片段支持
Vue2:
v-for?在?<template>?上使用時,不能設置?keyVue3:
<template v-for>?可以有?key,但應該放在子元素上
運行
<!-- Vue3 中正確的做法 -->
<template v-for="item in items"><div :key="item.id">{{ item.name }}</div><div :key="item.id + '-desc'">{{ item.desc }}</div>
</template>最佳實踐
始終為?
v-for?提供唯一的?key?屬性避免在同一元素上同時使用?
v-for?和?v-if在 Vue3 中,對于復雜的列表操作,考慮使用?
ref?和?reactive使用計算屬性處理需要過濾或排序的列表
Vue3 的這些變化主要是為了提供更一致的開發體驗和更好的性能,大多數?v-for?的基本用法在 Vue2 和 Vue3 中是相同的。