简介:本文旨在用最短的篇幅和例子,代入大家入门vue,也是本博主的一个学习记录,本文主要介绍的组件有,v-for。
v-for
功能:该指令可以遍历对象的属性,或者列表。
学习代码1:
<!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>v-for</title> <script src="../js/vue.js"></script> </head> <body> <div id="app"> <span v-for="(value, key, index) in person"> <!-- index是v-for内置的一个属性,从0开始 --> <!-- 然后js,key,value就是js中类的键值对 --> 索引:{{index}} -- 键:{{key}} -- 值: {{value}} <br> </span> </div> </body> <script> const app = new Vue({ el:"#app", data:{ person:{ name:"小陈", age:20 }, city:["武汉", "杭州", "合肥"], persons:[ {id:"1", name:"小陈", age:20, city:"武汉"}, {id:"2", name:"小王", age:20, city:"杭州"}, {id:"3", name:"小张", age:20, city:"合肥"}, ] }, methods:{ } }); </script> </html>
运行结果:
学习代码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>v-for</title> <script src="../js/vue.js"></script> </head> <body> <div id="app"> <span v-for="(value,key) in person"> <!-- 如果不写的话,最后索引是没有具体数值的 --> 索引:{{index}} -- 键:{{key}} -- 值: {{value}} <br> </span> </div> </body> <script> const app = new Vue({ el:"#app", data:{ person:{ name:"小陈", age:20 }, city:["武汉", "杭州", "合肥"], persons:[ {id:"1", name:"小陈", age:20, city:"武汉"}, {id:"2", name:"小王", age:20, city:"杭州"}, {id:"3", name:"小张", age:20, city:"合肥"}, ] }, methods:{ } }); </script> </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>v-for</title> <script src="../js/vue.js"></script> </head> <body> <div id="app"> <!-- :key是自定义键 --> <!-- 这里是将索引设置为key --> <ul v-for="(item, index) in city" :key="index"> <li> 索引:{{index}} -- 元素:{{item}}</li> </ul> </div> </body> <script> const app = new Vue({ el:"#app", data:{ person:{ name:"小陈", age:20 }, city:["武汉", "杭州", "合肥"], persons:[ {id:"1", name:"小陈", age:20, city:"武汉"}, {id:"2", name:"小王", age:20, city:"杭州"}, {id:"3", name:"小张", age:20, city:"合肥"}, ] }, methods:{ } }); </script> </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>v-for</title> <script src="../js/vue.js"></script> </head> <body> <div id="app"> <!-- 对于多重类的遍历方式 --> <div v-for="(person,index) in persons" :key="person.id"> 索引:{{index}} -- {{person.name}} {{person.age}} {{person.city}} </div> </div> </body> <script> const app = new Vue({ el:"#app", data:{ person:{ name:"小陈", age:20 }, city:["武汉", "杭州", "合肥"], persons:[ {id:"1", name:"小陈", age:20, city:"武汉"}, {id:"2", name:"小王", age:20, city:"杭州"}, {id:"3", name:"小张", age:20, city:"合肥"}, ] }, methods:{ } }); </script> </html>
运行结果: