gitHub地址:https://github.com/huangpna/vue_learn/example里面的lesson03
一 v-for循环数组
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index1</title> <style> li{ font-size:25px; list-style:none; } </style> </head> <body> <div id="app1"> <!--v-for循环数组--> <ul> <li v-for="item in listData">{{item.message}}</li> </ul> <ul> <li v-for="(item,index) in listData"> <!--第二个参数:可选参数,index:当前项的索引--> <span>{{index}}</span> <span>{{item.message}}</span> </li> </ul> </div> </body> <script src="../js/vue.min.js"></script> <script> var vm = new Vue({ el:'#app1', data:{ listData: [ /*注意:listData是一个数组*/ { message: 'Foo' }, { message: 'Bar' } ] } }); </script> </html>
输出结果:Foo Bar ,0 Foo 1 Bar
注意:也可以用of替代in作为分隔符,因为他是最接近javascript迭代器的语法。
一 v-for循环对象
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index3</title> <style> li{ font-size:25px; list-style:none; } </style> </head> <body> <div id="app2"> <!--v-for循环对象--> <ul> <li v-for="(item,key,index) in listData"> <!--第二个参数为键名 第三个参数为索引--> <span>{{key}}:</span> <span>{{item}}</span> </li> </ul> </div> </body> <script src="../js/vue.min.js"></script> <script> var vm = new Vue({ el:'#app2', data:{ listData: { firstName: 'John', lastName: 'Doe', age: 30 } } }); </script> </html>
输出结果:firstName: John,lastName: Doe,age: 30