技术文摘
Vue3 实现简易微信右滑删除逻辑的方法
2025-01-10 18:56:10 小编
Vue3 实现简易微信右滑删除逻辑的方法
在许多移动端应用中,微信右滑删除的交互逻辑十分常见,它为用户提供了便捷的操作体验。在 Vue3 项目中,我们也可以轻松实现这一功能。
创建一个基本的 Vue3 组件结构。在模板部分,我们创建一个列表来展示数据项,每个数据项都将具备右滑删除的功能。例如:
<template>
<div>
<div v-for="(item, index) in list" :key="index" class="item">
<!-- 内容区域 -->
<div class="content">{{ item }}</div>
<!-- 删除按钮,初始隐藏 -->
<button class="delete-btn" @click="deleteItem(index)">删除</button>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
const list = ref(['item1', 'item2', 'item3']);
const deleteItem = (index) => {
list.value.splice(index, 1);
};
</script>
<style scoped>
.item {
position: relative;
display: flex;
align-items: center;
padding: 10px;
border-bottom: 1px solid #ccc;
}
.content {
flex: 1;
}
.delete-btn {
position: absolute;
right: -80px;
background-color: red;
color: white;
border: none;
padding: 5px 10px;
transition: right 0.3s ease;
}
</style>
接下来,实现右滑效果。通过监听触摸事件,我们可以获取用户的滑动距离。在 <script setup> 中添加以下代码:
const startX = ref(0);
const currentIndex = ref(null);
const touchstartHandler = (e, index) => {
startX.value = e.touches[0].clientX;
currentIndex.value = index;
};
const touchmoveHandler = (e) => {
if (currentIndex.value!== null) {
const moveX = e.touches[0].clientX;
const distance = startX.value - moveX;
const deleteBtn = document.querySelector(`.delete-btn[data-index="${currentIndex.value}"]`);
if (distance > 0) {
deleteBtn.style.right = `${Math.min(0, -distance)}px`;
}
}
};
const touchendHandler = () => {
currentIndex.value = null;
const deleteBtns = document.querySelectorAll('.delete-btn');
deleteBtns.forEach((btn) => {
btn.style.right = '-80px';
});
};
然后,在模板中的 item 元素上绑定触摸事件:
<div v-for="(item, index) in list" :key="index" class="item"
@touchstart="touchstartHandler($event, index)"
@touchmove="touchmoveHandler($event)"
@touchend="touchendHandler($event)">
<!-- 内容区域 -->
<div class="content">{{ item }}</div>
<!-- 删除按钮,初始隐藏 -->
<button class="delete-btn" @click="deleteItem(index)">删除</button>
</div>
通过以上步骤,我们在 Vue3 中实现了简易的微信右滑删除逻辑。这种交互逻辑的实现,不仅提升了用户体验,也为我们的应用增添了更多便捷的操作方式,让数据管理变得更加高效。
- SQL Server 数据库日志文件收缩的操作之道
- SQLSERVER 死锁的查找与解决方法(推荐)
- MySQL 表的四种备份实现途径
- Oracle 与 SqlServer 差异大吗
- MySQL 中 where 与 having 的差异与相同之处
- MySQL 中基于父级的子集查询
- SqlServer 死锁的查询与解锁之道
- SQL 查询数据存在与否的实现范例
- SQLServer 数据库规模过度膨胀的优化策略
- 大型项目里 Java 连接 MSSQL 的性能优化策略
- Linux 环境下 SQL Server 数据库的安装与使用详解
- MySQL 批量查询获取每组最新数据
- 深度剖析 MySQL 双写缓冲区
- SQL Server 实现删除重复数据并只保留一条的步骤
- SQL Server 复制删除发布时错误 18752 的问题与解决之道