Vuejs学习笔记(一)-12.v-for循环遍历
v-for用于循环遍历
一、遍历数组
界面有个ul和li的标签,需要在页面循环遍历动态展示多个li标签。
使用item表示数组中每一个元素,index表示索引值,索引值从0开始
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>01 v-for遍历数组</title>
</head>
<body>
<div id="app">
<!-- 1.在遍历中没有使用下标索引值-->
<ul>
<li v-for="s in songs">{{ s }}</li>
</ul>
<!-- 2.在遍历中使用下标索引需要使用到item和index-->
<ul>
<li v-for="(item,index) in songs">{{ index }}.{{ item }}</li>
</ul>
</div>
</body>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
songs: ['not need freedom', 'square', 'world is ok', 'they']
}
})
</script>
</html>
二、遍历对象
可以调用对象中的value,index,
代码如下:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>02 v-for遍历对象</title> 6 </head> 7 <body> 8 <div id="app"> 9 <h2>{{ message }}</h2> 10 <!-- 方式1:获取对象所有的value值--> 11 <ul> 12 <li v-for="item in info">{{ item }}</li> 13 </ul> 14 <!-- 方式2:获取对象所有的key和value值--> 15 <ul> 16 <li v-for="(value,key) in info">{{key}}-{{value}}</li> 17 </ul> 18 <!-- 方式3:获取对象所有的key和value值index值--> 19 <ul> 20 <li v-for="(value,key,index) in info">{{index}}-{{key}}-{{value}}</li> 21 </ul> 22 </div> 23 <script src="../js/vue.js"></script> 24 <script> 25 const app = new Vue({ 26 el: '#app', 27 data: { 28 message: 'hello', 29 info: { 30 name: 'invoker', 31 age: 1000, 32 skillCount: 10 33 } 34 } 35 }) 36 </script> 37 </body> 38 </html>
三、官方推荐使用v-for时,加上:key属性,性能更优
key的作用是为了搞笑的更新虚拟dom
以上原理不是太清楚。一下是代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>03 v-for 添加key</title> </head> <body> <div id="app"> <h2>{{ message }}</h2> <!-- 方式1的性能差(数组的值越多,中间插入值时的性能越差)--> <ul> <li v-for="item1 in letters">{{ item1 }}</li> </ul> <!-- 方式2的性能好--> <ul> <li v-for="item2 in letters" :key="item2">{{ item2 }}</li> </ul> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: 'hello', letters: ['A', 'B', 'C', 'D', 'E', 'F'] } }) </script> </body> </html>
本文来自博客园,作者:kaer_invoker,转载请注明原文链接:https://www.cnblogs.com/invoker2021/p/14958714.html

浙公网安备 33010602011771号