Vue.js基础-04-循环语句(遍历数组、迭代对象属性、遍历数组范围)
文章目录
1. 遍历数组
1.1 < li > 标签中使用
语法示例
<li v-for="site in sites">{{ site.name }} : {{site.attack}}</li>
完整示例
- 代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CROW SONG</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<ol>
<li v-for="site in sites">{{ site.name }} : {{site.attack}}</li>
</ol>
</div>
<script>
new Vue({
el: "#app",
data: {
sites: [
{ name: "关羽", attack: 95 },
{ name: "张飞", attack: 90 },
{ name: "赵云", attack: 97 },
{ name: "马超", attack: 92 },
{ name: "黄忠", attack: 88 },
],
},
});
</script>
</body>
</html>
- 打印结果
1.2 模板中使用
语法示例
<ul>
<template v-for="site in sites">
<li > xxxxxxx </li>
</template>
</ul>
完整示例
- 代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CROW SONG</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<ul>
<template v-for="site in sites">
<li >{{ site.name }} : {{site.attack}}</li>
<li>====================</li>
</template>
</ul>
</div>
<script>
new Vue({
el: "#app",
data: {
sites: [
{ name: "关羽", attack: 95 },
{ name: "张飞", attack: 90 },
{ name: "赵云", attack: 97 },
{ name: "马超", attack: 92 },
{ name: "黄忠", attack: 88 },
],
},
});
</script>
</body>
</html>
- 输出
2. 迭代对象属性
对象有三个值,按顺序一次是:value,key,index。
我们用以下示例测试:
2.1 迭代第一个参数(值)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CROW SONG</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<ul>
<li v-for="info in object">
{{ info }}
</li>
</ul>
</div>
<script>
new Vue({
el: '#app',
data: {
object: {
name: '关羽',
belong: '蜀',
attack: 98
}
}
})
</script>
</body>
</html>
- 输出
2.2 迭代第二个参数(键名)
<div id="app">
<ul>
<li v-for="(value,key) in object">
{{ key }} : {{value}}
</li>
</ul>
</div>
- 显示结果
2.3 第三个参数(索引值)
<div id="app">
<ul>
<li v-for="(value,key,index) in object">
{{index}} : {{ key }} : {{value}}
</li>
</ul>
</div>
3. 遍历整数范围
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CROW-宋</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<ul>
<li v-for="n in 8">
{{ n }}
</li>
</ul>
</div>
<script>
new Vue({
el: '#app'
})
</script>
</body>
</html>
- 结果输出