vue实现滑动删除组件
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>
注意事项
- 移动端需要添加
touch-action: pan-y样式防止浏览器默认行为干扰 - 考虑添加防抖处理避免快速滑动时的抖动
- 可以扩展支持右侧滑动操作
- 在列表中使用时需要注意每个项目的独立状态管理
这个实现包含了基本的滑动删除功能,可以根据实际需求进一步扩展和完善。







