循环使用 v-for 指令。
v-for 指令需要以 site in sites 形式的特殊语法, sites 是源数据数组并且 site 是数组元素迭代的别名。
v-for 可以绑定数据到数组来渲染一个列表:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>demo</title> </head> <body> <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script> <div id="demo"> <ol> <li v-for="site in sites"> {{site.name}} </li> </ol> </div> <script> new Vue({ el: '#demo', data: { sites:[ {name:"cyy1"}, {name:"cyy2"}, {name:"cyy3"} ] }, methods:{ }, filters:{//过滤器 } }) </script>
模板中使用 v-for:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>demo</title> </head> <body> <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script> <div id="demo"> <ul> <template v-for="site in sites"> <li>{{site.name}}</li> <li>-----------</li> </template> </ul> </div> <script> new Vue({ el: '#demo', data: { sites:[ {name:"cyy1"}, {name:"cyy2"}, {name:"cyy3"} ] }, methods:{ }, filters:{//过滤器 } }) </script>
v-for 可以通过一个对象的属性来迭代数据:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>demo</title> </head> <body> <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script> <div id="demo"> <ul> <li v-for="obj in object"> {{obj}} </li> </ul> </div> <script> new Vue({ el: '#demo', data: { object:{ name:"cyy1", age:25, sex:"girl" } }, methods:{ }, filters:{//过滤器 } }) </script>
也可以提供第二个的参数为键名:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>demo</title> </head> <body> <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script> <div id="demo"> <ul> <li v-for="(obj,key) in object"> {{key}}:{{obj}} </li> </ul> </div> <script> new Vue({ el: '#demo', data: { object:{ name:"cyy1", age:25, sex:"girl" } }, methods:{ }, filters:{//过滤器 } }) </script>
第三个参数为索引:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>demo</title> </head> <body> <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script> <div id="demo"> <ul> <li v-for="(obj,key,index) in object"> {{index}}.{{key}}:{{obj}} </li> </ul> </div> <script> new Vue({ el: '#demo', data: { object:{ name:"cyy1", age:25, sex:"girl" } }, methods:{ }, filters:{//过滤器 } }) </script>
v-for 也可以循环整数
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>demo</title> </head> <body> <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script> <div id="demo"> <ul> <li v-for="n in 10"> {{n}} </li> </ul> </div> <script> new Vue({ el: '#demo', data: { }, methods:{ }, filters:{//过滤器 } }) </script>
来源:https://www.cnblogs.com/chenyingying0/p/12377384.html