v-for的用法及案例

欢迎来到我的UniApp技术专栏!🎉 在这里,我将与大家分享关于UniApp开发的实用技巧、最佳实践和项目经验。

专栏特色:

📱 跨平台开发一站式解决方案

🚀 从入门到精通的完整学习路径

💡 实战项目经验分享

🔍 常见问题深度解析

无论你是刚接触UniApp的新手,还是有一定经验的开发者,都能在这里找到有价值的内容。我将持续更新最新技术动态和开发技巧,帮助大家提升开发效率,打造高质量的跨平台应用。

如果文章对你有帮助,别忘了点赞收藏🌟,也欢迎在评论区留言交流,我会及时回复大家的问题!

让我们一起探索UniApp的无限可能!

目录

一.v-for的用法

1.举例1

2.举例2

二.购物车案例

1.代码

2.存在的问题:复选框错位

[3.解决方案: 赋值给key属性一个唯一的值](#3.解决方案: 赋值给key属性一个唯一的值)


一.v-for的用法

1.举例1

html 复制代码
<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

html 复制代码
<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.代码

html 复制代码
<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属性赋一个唯一的值,如下:

运行效果:

以上就是本篇文章的全部内容,喜欢的话可以留个免费的关注呦~

相关推荐
志尊宝7 小时前
Vue3 零基础每日笔记(026):emit 子传父——defineEmits 与事件校验
前端·javascript·html·vue3
RuoyiOffice8 小时前
SpringBoot3+Vue3 库存盘点:账面和实盘对不上,差异单怎么走审批再调账
spring boot·vue3·erp·spring boot 3·库存盘点·盘盈盘亏
RuoyiOffice11 小时前
SpringBoot3+PaddleOCR 发票识别:不接云端大模型,本地飞桨怎么把专票读进进项单
spring boot·vue3·飞桨·paddleocr·spring boot 3·发票ocr·进项发票
平凡シンプル1 天前
TCP UDP 网络通信插件 SL-Uniplugin-Tcp-Udp
网络·学习·uniapp·记录
RuoyiOffice1 天前
SpringBoot3+Vue3 项目立项到甘特:审批冻结台账、任务树怎么汇进度
spring boot·项目管理·vue3·甘特图·wbs·spring boot 3·立项审批
RuoyiOffice3 天前
SpringBoot3+Vue3 招聘 Offer:发出、审批通过、转入职怎么走完
spring boot·vue3·offer·入职·spring boot 3·hrm·招聘管理
qq_350897217 天前
trea实用工具
vue.js·uniapp
9765033357 天前
iOS 上架/审核 4.3a全面解读-最新
flutter·ios·objective-c·uniapp
上单带刀不带妹8 天前
小程序图片缓存问题:时间戳和版本号解决图片不更新
缓存·小程序·vue·uniapp
RuoyiOffice9 天前
SpringBoot3+Vue3 最推荐的开源 OA 系统 2026:流程驱动、资源闭环、多端互通
spring boot·vue3·flowable·oa·协同办公·spring boot 3·开源oa