1、v-for遍历数组和对象
<ul> <li v-for="item in array">{{item}}</li><br> <li v-for="(item,index) in array">{{item}}--{{index}}</li><br> <li v-for="(value,key,index) in obj">{{value}}--{{key}}--{{index}}</li><br>
</ul>
2、v-for绑定和非绑定key的区别
加上key之后,能够更好的复用,减少资源的消耗。
<li v-for="item in list" :key="item">{{item}}</li>
没加key之前,如果向数组中间添加一个元素,要依次替换数组元素,
加上key之后,可以直接在数组中间插入这个元素。
*******完整代码******
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="./js/vue.js"></script> </head> <div id="app"> <ul> <li v-for="item in array">{{item}}</li><br> <li v-for="(item,index) in array">{{item}}--{{index}}</li><br> <li v-for="(value,key,index) in obj">{{value}}--{{key}}--{{index}}</li><br> </ul><br> <ul> <li v-for="item in list" :key="item">{{item}}</li> </ul> </div> <body> <script> let vm = new Vue({ el: '#app', data: () => ({ array: [ '王者荣耀', '和平精英', '绝地求生' ], obj: { name: '何欣航', age: '18', height: '1.80' }, list:['A','B','C','D','E'] }), methods: {} }) </script> </body> </html>
小案例:点击更换背景颜色
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="./js/vue.js"></script> <style> .active { background-color: yellowgreen; } </style> </head> <div id="app"> <ul> <li v-for="(item,index) in game" v-on:click="getClass(index)" :class="{active:cindex===index}">{{item}}</li> </ul> </div> <body> <script> let vm = new Vue({ el: '#app', data: () => ({ game: ['王者荣耀', '和平精英', '炉石传说', '穿越火线'], cindex: 0 }), methods: { getClass: function (index) { this.cindex = index } } }) </script> </body> </html>