在移动应用开发中,列表是常见的展示形式,而长按删除列表项也是一个实用且常见的交互功能。今天就来和大家分享如何在 UniApp 中实现列表的长按删除功能,同时附上详细的代码。
效果预览
通过代码实现后,我们将得到一个带有红色边框、圆角设计的列表。当用户长按列表中的某一项时,会弹出确认删除的提示框,用户确认后,对应的列表项将从列表中移除。
核心代码分析
1. 模板部分(<template>
)
<template>
<view>
<!-- 列表展示 -->
<view v-for="(item, index) in itemList" :key="index" @longpress="confirmDelete(index)" class="item">
{
{ item }}
</view>
</view>
</template>
2. 脚本部分(<script>
)
<script>
export default {
data() {
return {
// 模拟列表数据
itemList: ['列表项1', '列表项2', '列表项3', '列表项4']
};
},
methods: {
// 确认删除方法
confirmDelete(index) {
uni.showModal({
title: '提示',
content: '确定要删除该项吗?',
success: (res) => {
if (res.confirm) {
// 用户点击确认,删除对应列表项
this.itemList.splice(index, 1);
}
}
});
}
}
};
</script>
3. 样式部分(<style>
)
<style>
.item{
width: 90%;
padding: 20px;
border-radius: 12px;
background-color: white;
font-size: 20px;
justify-content: center;
display: flex;
border: 3rpx solid red;
margin-bottom: 10rpx;
}
</style>
总结
通过以上代码,我们可以在 UniApp 中轻松实现列表的长按删除功能。这种交互方式能提升用户体验,让用户更方便地管理列表数据。大家可以根据实际需求对列表的样式和数据进行调整,也可以在此基础上添加更多的交互逻辑。希望这个分享对你的 UniApp 开发有所帮助,如果你在使用过程中有任何问题,欢迎在评论区留言交流。
你可以将上述代码复制到自己的 UniApp 项目中进行测试和使用,快去试试吧!