v-for的用法及案例
目录
一.v-for的用法
1.举例1
2.举例2
二.购物车案例
1.代码
2.存在的问题:复选框错位
3.解决方案: 赋值给key属性一个唯一的值
一.v-for的用法
1.举例1
<template><view><view v-for="(item,index) in 10" :key="index">box模块-{{ index+1 }}</view></view>
</template><script setup></script><style lang="scss" scoped>
</style>
:key是生成的每一个view的唯一标志。
运行效果:
2.举例2
<template><view><view v-for="item in nba" :key="item.id">球星:{{item.name}} - 球衣:{{item.num}}</view></view>
</template><script setup>
import {ref} from 'vue';
const nba = ref([{id:1, name:"乔丹",num:23},{id:2, name:"詹姆斯",num:6},{id:3, name:"科比",num:24},
])</script><style lang="scss" scoped>
</style>
运行效果:
二.购物车案例
1.代码
<template><view class="out"><view class="item" v-for="(item,index) in goods"><checkbox></checkbox><text class="title">{{item.name}}</text><text class="del" @click="remove(index)">删除</text></view></view>
</template><script setup>
import {ref} from 'vue';
//定义商品对象数组
const goods = ref([{id:11, name:"小米"},{id:22, name:"华为"},{id:33, name:"oppo"},{id:44, name:"苹果"},
])
//点击【删除】按钮,触发的事件
const remove = (index)=>{goods.value.splice(index, 1);//删除下标为index的元素
}
</script><style lang="scss" scoped>
.out{padding:10px;.item{padding:10px 0;.del{color:red;margin-left: 30px;}}
}
</style>
运行效果:
2.存在的问题:复选框错位
当我们选中某一个商品的复选框后,如果自己/上面的商品被删除了,复选框会发生错位,如下图所示:
3.解决方案: 赋值给key属性一个唯一的值
此时是vue底层算法问题,要想解决该问题,就得给使用v-for渲染的每一个项的key属性赋一个唯一的值,如下:
运行效果:
以上就是本篇文章的全部内容,喜欢的话可以留个免费的关注呦~