当前位置:首页 > VUE

vue实现滑动删除组件

2026-01-21 14:37:12VUE

Vue 实现滑动删除组件的方法

滑动删除是移动端常见的交互模式,可以通过 Vue 实现一个可复用的组件。以下是实现的核心思路和代码示例:

基础结构设计

使用 Vue 的模板部分定义滑动区域和删除按钮:

<template>
  <div class="swipe-container">
    <div 
      class="swipe-content"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      :style="{ transform: `translateX(${offsetX}px)` }"
    >
      <!-- 主内容区域 -->
      <slot></slot>
    </div>
    <div class="swipe-action">
      <button @click="$emit('delete')">删除</button>
    </div>
  </div>
</template>

触摸事件处理

在脚本部分实现触摸逻辑:

<script>
export default {
  data() {
    return {
      startX: 0,
      offsetX: 0,
      isDragging: false
    }
  },
  methods: {
    handleTouchStart(e) {
      this.startX = e.touches[0].clientX
      this.isDragging = true
    },
    handleTouchMove(e) {
      if (!this.isDragging) return
      const currentX = e.touches[0].clientX
      const diff = currentX - this.startX

      // 限制向左滑动最大距离
      if (diff < 0) {
        this.offsetX = Math.max(diff, -100) // -100是最大滑动距离
      }
    },
    handleTouchEnd() {
      this.isDragging = false
      // 滑动超过阈值时保持打开状态
      if (this.offsetX < -50) {
        this.offsetX = -80 // 保持打开的位移量
      } else {
        this.offsetX = 0 // 恢复原位
      }
    }
  }
}
</script>

样式处理

添加必要的 CSS 样式:

<style scoped>
.swipe-container {
  position: relative;
  overflow: hidden;
  width: 100%;
}

.swipe-content {
  position: relative;
  z-index: 2;
  background: white;
  transition: transform 0.3s ease;
}

.swipe-action {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 1;
  width: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ff5252;
}
</style>

使用动画优化

可以添加过渡效果使滑动更流畅:

.swipe-content {
  will-change: transform;
  transition: transform 0.2s cubic-bezier(0.22, 0.61, 0.36, 1);
}

组件使用示例

在父组件中这样使用:

<swipe-delete @delete="handleDelete">
  <div>可滑动删除的内容项</div>
</swipe-delete>

注意事项

  1. 移动端需要添加 touch-action: pan-y 样式防止浏览器默认行为干扰
  2. 考虑添加防抖处理避免快速滑动时的抖动
  3. 可以扩展支持右侧滑动操作
  4. 在列表中使用时需要注意每个项目的独立状态管理

这个实现包含了基本的滑动删除功能,可以根据实际需求进一步扩展和完善。

vue实现滑动删除组件

标签: 组件vue
分享给朋友:

相关文章

vue 页签实现

vue 页签实现

Vue 页签实现方法 在 Vue 中实现页签功能通常涉及动态组件、路由或状态管理。以下是几种常见的实现方式: 使用动态组件 通过 Vue 的 <component> 动态组件结合 v-…

vue前端分页怎么实现

vue前端分页怎么实现

前端分页实现方法 在Vue中实现前端分页通常涉及数据分割和页面控制逻辑。以下是常见的实现方式: 使用计算属性分页 通过计算属性对数据进行切片处理: computed: { paginatedD…

vue实现字母添加排序

vue实现字母添加排序

实现字母添加排序的方法 在Vue中实现字母添加排序功能,可以通过以下步骤完成: 创建Vue实例并定义数据 new Vue({ el: '#app', data: { letters…

vue聊天实现

vue聊天实现

Vue 聊天应用实现步骤 创建 Vue 项目 使用 Vue CLI 或 Vite 初始化项目,安装必要依赖(如 Vue 3、Element UI 或 Vuetify 用于 UI 组件)。 npm c…

vue实现截图

vue实现截图

Vue 实现截图的方法 使用 html2canvas 库 安装 html2canvas 库: npm install html2canvas 在 Vue 组件中使用: import html2…

vue实现公式

vue实现公式

在Vue中实现公式展示或计算可以通过多种方式实现,以下为具体方法: 使用模板插值与计算属性 若公式较简单,可直接在模板中使用插值表达式或计算属性。例如计算圆的面积: <templat…