一、什么是v-for指令
在Vue.js中,我们可以使用v-for指令基于源数据重复渲染元素。也就是说可以使用v-for指令实现遍历功能,包括遍历数组、对象、数组对象等。
二、遍历数组
代码示例如下:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Document</title>
- <!--引入vue.js-->
- <script src="node_modules/vue/dist/vue.js" ></script>
- <script>
- window.onload=function(){
- // 构建vue实例
- new Vue({
- el:"#my",// el即element,表示挂载的元素,不能挂载在HTML和body元素上面
- data:{
- array:[1,2,3,4],//数组
- },
- // 方法
- methods:{
-
- }
- })
- }
- </script>
- </head>
- <body>
- <div id="my">
- <div>
- <h1>下面的使用v-for遍历数组</h1>
- <div>
- <h1>只显示值</h1>
- <ul>
- <li v-for=" v in array">{{v}}</li>
- </ul>
- </div>
- <div>
- <h1>显示值和索引</h1>
- <ul>
- <li v-for=" (v,index) in array">值:{{v}},对应的索引:{{index}}</li>
- </ul>
- </div>
- </div>
- </div>
- </body>
- </html>
其中index表示数组的索引
效果如下图所示:

注意:最新的版本中已经移除了$index获取数组索引的用法
三、遍历对象
代码示例如下:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Document</title>
- <!--引入vue.js-->
- <script src="node_modules/vue/dist/vue.js" ></script>
- <script>
- window.onload=function(){
- // 构建vue实例
- new Vue({
- el:"#my",// el即element,表示挂载的元素,不能挂载在HTML和body元素上面
- data:{
- array:[1,2,3,4],//数组
- },
- // 方法
- methods:{
-
- }
- })
- }
- </script>
- </head>
- <body>
- <div id="my">
- <div>
- <h1>下面的使用v-for遍历数组</h1>
- <div>
- <h1>只显示值</h1>
- <ul>
- <li v-for=" v in array">{{v}}</li>
- </ul>
- </div>
- <div>
- <h1>显示值和索引</h1>
- <ul>
- <li v-for=" (v,index) in array">值:{{v}},对应的索引:{{index}}</li>
- </ul>
- </div>
- </div>
- </div>
- </body>
- </html>
效果如下图所示:

四、遍历数组对象
代码示例如下:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>使用v-for指令遍历数组对象</title>
- <!--引入vue.js-->
- <script src="node_modules/vue/dist/vue.js" ></script>
- <script>
- window.onload=function(){
- // 构建vue实例
- new Vue({
- el:"#my",// el即element,表示挂载的元素,不能挂载在HTML和body元素上面
- data:{
- lists:[
- {name:"kevin",age:23},
- {name:"tom",age:25},
- {name:"joy",age:28}
- ]
- },
- // 方法
- methods:{
-
- }
- })
- }
- </script>
- </head>
- <body>
- <div id="my">
- <div>
- <h1>下面的使用v-for遍历数组对象</h1>
- <div>
- <h1>只显示值</h1>
- <ul>
- <li v-for=" list in lists">name值:{{list.name}},age值:{{list.age}}</li>
- </ul>
- </div>
- <div>
- <h1>显示值和键</h1>
- <ul>
- <li v-for=" (list,index) in lists">name值:{{list.name}},age值:{{list.age}}, 对应的键:{{index}}</li>
- </ul>
- </div>
- </div>
- </div>
- </body>
- </html>
效果如下图所示:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。