v-for迭代分為數(shù)組迭代和對象迭代
作用: 控制HTML元素中的循環(huán)盯另,實現(xiàn)語句列表的生成
用法: v-for = “item in 集合”古程,其中item指集合的子項球及,集合指被遍歷的元素,通常為數(shù)組
用處: 用處:寫在誰上邊,誰遍歷
數(shù)組迭代
栗子1:
運行結(jié)果 :
栗子2: 可以使用of代替in來使用
運行結(jié)果 :
foo
bar
jewel
栗子3: v-for還支持第二個可選參數(shù)作為當(dāng)前項的索引
運行結(jié)果 :
Parent - 0 - foo
Parent - 1 - bar
栗子4: 可以用template渲染多個元素塊
運行結(jié)果 :
栗子5: 整數(shù)迭代
運行結(jié)果 : 1 2 3 4 5 6 7 8 9 10
栗子6: 也可以將10替換成一個變量疾棵,從data中提取數(shù)據(jù)
運行結(jié)果 : 1 2 3 4 5 6 7 8
對象迭代
栗子1:默認遍歷的是value的值
運行結(jié)果 :
john
bob
30
栗子2: 可以提供第二個參數(shù)作為鍵名
運行結(jié)果 :
FirstName : john
lastName : bob
Age : 30
栗子3:還可以接受第三個參數(shù)作為索引
運行結(jié)果 :
0 : FirstName : john
1 : lastName : bob
2 : Age : 30
v-if and v-for
when they exist on the same node,v-for has a highter priority than v-if,that means the v-if will be run on each oteration of the loop separately.this is vary useful when you want to render nodes for only some items
舉個栗子
運行結(jié)果 :
hello : 0
world : 1
新增兩個例子痹仙,分別對應(yīng)數(shù)字排序和對象的屬性排序
1. 數(shù)字排序
在JavaScript中是尔,默認的排序方式是按照ascll碼排序,即12排在1和3之間开仰,所以需要用sortNumber函數(shù)將其轉(zhuǎn)化成數(shù)字間的排序
在data中存放的是一組或一個數(shù)據(jù)拟枚,最好不要進行數(shù)據(jù)將的處理(比如排序,轉(zhuǎn)化成大小寫等)众弓,這些計算屬性我們可以放在computed中進行
轉(zhuǎn)自作者:椰果粒