循环需要v-for指令。
v-for需要以site in sites形式的特殊语法,sites是源数据并且sites是数组元素迭代的别名。
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>
</head>
<body>
<div id="app">
<!-- 1.遍历过程没有使用索引(下标值) -->
<ul>
<li v-for="item in names">{{item}}</li>
</ul>
<!-- 2.遍历过程有使用索引(下标值) -->
<ul>
<li v-for="(item,index) in names">{{index+":"+item}}</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data: {
names: ["zzz", "ttt", "yyy"]
}
})
</script>
</body>
</html>
模板中使用v-for
v-for
<ul>
<template v-for="site in sites">
<li>{{ site.name }}</li>
<li>--------------</li>
</template>
</ul>
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>
</head>
<body>
<div id="app">
<!-- 1.遍历过程没有使用index索引-->
<!-- 格式为:(value, name) -->
<ul>
<li v-for="(item,key) in user">{{key+"-"+item}}</li>
</ul>
<!-- 格式为:(value, name, index) -->
<ul>
<li v-for="(item,key,index) in user">{{key+"-"+item+"-"+index}}</li>
</ul></div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data: {
user: {
name: "zzz",
height: 188,
age: 24
}
}
})
</script>
</body>
</html>
1.遍历过程没有使用index索引,item表示当前元素是属性值,key表示user表示user对象属性名。
2. 遍历过程使用索引,index表示索引从0开始。