01-v-for遍历数组
遍历时需要和不需要下标的情况
<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+1}},{{item}}</li>
</ul>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data: {
names: ["1", "2", "3", "4", "5"],
},
});
</script>
</body>
结果:
1
2
3
4
5
1,1
2,2
3,3
4,4
5,5
02-v-for遍历对象
对象跟数组不同,对象有键值对还有下标
<body>
<div id="app">
<!--1.在遍历对象的过程中,如果只是获取一个值,那么获取到的是value-->
<ul>
<li v-for="item in info">{{item}}</li>
</ul>
<!--2.获取key和value (value, key) -->
<ul>
<li v-for="(value, key) in info">{{value}}-{{key}}</li>
</ul>
<!--3. 获取key和value和index 格式: (value, key, index) -->
<ul>
<li v-for="(value, key, index) in info">
{{value}}-{{key}}-{{index}}
</li>
</ul>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data: {
info: {
name: "小影",
age: 3,
height: 110,
},
},
});
</script>
</body>
03-小案例
实现功能:遍历数组遍历,点击对应元素时,该元素变颜色,其他元素颜色变回来
<style>
.active {
color: hotpink;
}
</style>
<body>
<div id="app">
<ul>
<li
v-for="(item,index) in movies"
:class="{active:thisIndex === index}"
@click="change(index)"
>
{{index}}{{item}}
</li>
</ul>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data: {
movies: ["天气之子", "言叶之庭", "飞翔", "废墟"],
thisIndex: 0,
},
methods: {
change(index) {
this.thisIndex = index;
},
},
});
</script>
</body>