Vue2入门之超详细教程十二-列表渲染
1、简介
V-for指令:
1. 用于展示列表数据
2. 语法:v-for=”(item,index) in xxx ”:key=”yyy”
3. 可遍历:数组、对象、字符串(用的很少)、指定次数(用的很少)
学习Vue之前最后会一些HTML和CSS的基础知识,HTML基础知识 传送门,CSS基础知识 传送门。
2、列表渲染
1. 基本列表
(1)遍历数组
在vscode中创一个新目录,叫“11_列表渲染”,在下面创建一个“1基本列表.html”文件,在里面输入以下代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script type="text/javascript" src="../js/development/vue.js"></script> </head> <body> <div id="root"> <h2>人员列表:</h2> <ul> <li v-for="p in persons" :key="p.id">{{p.name}}-{{p.age}}</li> </ul> <ul> <li v-for="(p,index) in persons" :key="p.id">{{p.name}}-{{p.age}}</li> </ul> </div> <script type="text/javascript"> Vue.config.productionTip=false const vm = new Vue({ el:"#root", data:{ persons:[ {id:'001',name:'张三',age:18}, {id:'002',name:'李四',age:19}, {id:'003',name:'王五',age:20} ] } }) </script> </body> </html>
V-for可以用来变量数据,以上案例是遍历了数组,有两种写法:
<li v-for="p in persons" :key="p.id">{{p.name}}-{{p.age}}</li>
和
<li v-for="(p,index) in persons" :key="p.id">{{p.name}}-{{p.age}}</li>
尽量用第二种方法
(2)遍历对象
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script type="text/javascript" src="../js/development/vue.js"></script> </head> <body> <div id="root"> <!-- 遍历对象 --> <h2>汽车信息</h2> <ul> <li v-for="(value,k) in car" :key="k"> {{k}}-{{value}} </li> </ul> </div> <script type="text/javascript"> Vue.config.productionTip=false const vm = new Vue({ el:"#root", data:{ car:{ name:'奥迪A8', price:'70W', color:'黑色' } } }) </script> </body> </html>
(3)遍历字符串
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script type="text/javascript" src="../js/development/vue.js"></script> </head> <body> <div id="root"> <!-- 遍历字符串 --> <h2>汽车信息</h2> <ul> <li v-for="(s,index) in str"> {{s}}-{{index}} </li> </ul> </div> <script type="text/javascript"> Vue.config.productionTip=false const vm = new Vue({ el:"#root", data:{ str:'hello' } }) </script> </body> </html>
(4)遍历指定次数
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script type="text/javascript" src="../js/development/vue.js"></script> </head> <body> <div id="root"> <!-- 遍历字符串 --> <h2>汽车信息</h2> <ul> <li v-for="(number,index) in 5"> {{number}}-{{index}} </li> </ul> </div> <script type="text/javascript"> Vue.config.productionTip=false const vm = new Vue({ el:"#root", data:{ str:'hello' } }) </script> </body> </html>