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 中实现了简易的微信右滑删除逻辑。这种交互逻辑的实现,不仅提升了用户体验,也为我们的应用增添了更多便捷的操作方式,让数据管理变得更加高效。

TAGS: Vue3 前端开发 逻辑实现 微信右滑删除

欢迎使用万千站长工具!

Welcome to www.zzTool.com