技术文摘
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 中实现了简易的微信右滑删除逻辑。这种交互逻辑的实现,不仅提升了用户体验,也为我们的应用增添了更多便捷的操作方式,让数据管理变得更加高效。
- HTML中指定最小值的方法
- 用Vue 3和Composition API创建报告应用程序的方法
- CSS选择子元素的使用
- 掌握 JavaScript 编码:第 2 部分之条件
- CSS 语音媒体属性 voice-range
- 辅助功能了解:第 5 部分
- 深入解析:自定义 jQuery UI 小部件主题的全面指南
- CSS 中 :link 伪类的使用方法
- JavaScript NodeList转数组的最快方式
- 在HTML里把three.js背景设为透明或其他颜色
- FabricJS:怎样在Line对象的URL字符串中设置质量级别
- CSS 中 margin 属性怎么用
- Particles.js基础知识入门
- 进阶秘籍:精灵的精妙运用
- HTML 和 CSS 打造现代侧边栏菜单的方法