v-for
v-for
指令可以绑定数组的数据来渲染一个项目列表
v-for
指令需要使用item in items
形式的特殊语法,items
是源数据数组并且item
是数组元素迭代的别名。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <!-- 开发环境版本 --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <ol> <li v-for="todo in todos"> {{ todo.text }} </li> </ol> </div> </body> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { todos: [ { text: '学习 JavaScript' }, { text: '学习 Vue' }, { text: '整个牛X项目' } ] } }) </script> </html>
拿到for循环的index
<ol> <li v-for="(todo,index) in todos"> {{ todo.text }}-{{index}} </li> </ol>
for循环对象
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <!-- 开发环境版本 --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <ul> <li v-for="value in object"> {{ value }} </li> </ul> </div> </body> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { object: { title: 'How to do lists in Vue', author: 'Jane Doe', publishedAt: '2016-04-10' } } }) </script> </html>
效果:
for循环对象列表
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <!-- 开发环境版本 --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <ul> <li v-for="item in items"> {{ item.title }}~~~{{item.author}}~~~{{item.publishedAt}} </li> </ul> </div> </body> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { items: [ { title: 'Vue', author: 'Jane Doe', publishedAt: '2016-04-10' }, { title: 'python', author: 'Ricky', publishedAt: '2019-04-10' }, { title: 'itcast', author: 'itcast', publishedAt: '2006-05-08' } ] } }) </script> </html>
效果: