vue v-for(list rendering)

v-for迭代分为数组迭代和对象迭代

  1. 作用 : 控制HTML元素中的循环,实现语句列表的生成
  2. 用法 : v-for = “item in 集合”,其中item指集合的子项,集合指被遍历的元素,通常为数组
  3. 用处 : 用处:写在谁上边,谁遍历
数组迭代

栗子1

vue v-for(list rendering)_第1张图片

运行结果 :
vue v-for(list rendering)_第2张图片

栗子2 : 可以使用of代替in来使用

    
  • {{ item.message }}
var app = new Vue({ el : '#app', data : { items : [ {message : 'foo'}, {message : 'bar'}, {message : 'jewel'} ] } })

运行结果 :
 foo
 bar
 jewel
栗子3 : v-for还支持第二个可选参数作为当前项的索引

    
  • {{ parentMessage }} - {{ index }} - {{ item.message }}
var app2 = new Vue({ el : '#app2', data : { parentMessage : 'Parent', items : [ { message : 'foo'}, { message : 'bar'} ] } })

运行结果 :
Parent - 0 - foo
Parent - 1 - bar
栗子4 : 可以用template渲染多个元素块

var app2 = new Vue({ el : '#app2', data : { parentMessage : 'Parent', items : [ { message : 'foo'}, { message : 'bar'} ] } })

运行结果 :

vue v-for(list rendering)_第3张图片

栗子5 : 整数迭代

    
{{ n }}
var app4 = new Vue({ el : '#app4' });

运行结果 : 1 2 3 4 5 6 7 8 9 10
栗子6 : 也可以将10替换成一个变量,从data中提取数据

    
{{ n }}
var app4 = new Vue({ el : '#app4', data : { m : 8 } })

运行结果 : 1 2 3 4 5 6 7 8

对象迭代

栗子1 :默认遍历的是value的值

  • {{ value }}
var app3 = new Vue({ el : '#app3', data : { object : { FirstName : 'john', lastName : 'bob', Age : 30 } } })

运行结果 :
 john
 bob
 30
栗子2 : 可以提供第二个参数作为键名

  • {{ key }} : {{ value }}

运行结果 :
 FirstName : john
 lastName : bob
 Age : 30
栗子3 :还可以接受第三个参数作为索引

  • {{ index }} : {{ key }} : {{ value }}

运行结果 :
 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
举个栗子

    
  • {{ todo }} : {{ index }}
var app6 = new Vue({ el : '#app6', data : { todos : ['hello', 'world', 'a', 'b', 'v'] } });

运行结果 :
hello : 0
world : 1


新增两个例子,分别对应数字排序和对象的属性排序
1. 数字排序

  • {{num}}
  • var app = new Vue({ el : '#app', data : { number : [1,2,3,4,5,11,32,25] // 元素极其相似,那么就放在数组中 }, computed : { sortItem : function(){ return this.number.sort(sortNumber); } } }) function sortNumber(a,b){ // 此函数代表了对数字的排序算法。 return a-b; }

    在JavaScript中,默认的排序方式是按照ascll码排序,即12排在1和3之间,所以需要用sortNumber函数将其转化成数字间的排序
    在data中存放的是一组或一个数据,最好不要进行数据将的处理(比如排序,转化成大小写等),这些计算属性我们可以放在computed中进行

    你可能感兴趣的:(vue v-for(list rendering))