目錄
一.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屬性賦一個唯一的值,如下:
運行效果:
以上就是本篇文章的全部內容,喜歡的話可以留個免費的關注呦~