vue实现滑动删除
Vue 实现滑动删除功能
滑动删除是移动端常见的交互方式,可以通过 Vue 结合手势事件或第三方库实现。以下是两种常见的实现方法:
使用 Touch 事件原生实现
通过监听 touchstart、touchmove 和 touchend 事件计算滑动距离,动态调整元素位置。
<template>
<div class="list-container">
<div
v-for="(item, index) in list"
:key="index"
class="list-item"
@touchstart="handleTouchStart($event, index)"
@touchmove="handleTouchMove($event, index)"
@touchend="handleTouchEnd(index)"
:style="{ transform: `translateX(${item.offsetX}px)` }"
>
<div class="content">{{ item.text }}</div>
<div class="delete-btn" @click="deleteItem(index)">删除</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{ text: 'Item 1', offsetX: 0 },
{ text: 'Item 2', offsetX: 0 }
],
startX: 0
}
},
methods: {
handleTouchStart(e, index) {
this.startX = e.touches[0].clientX
},
handleTouchMove(e, index) {
const currentX = e.touches[0].clientX
const offsetX = currentX - this.startX
if (offsetX < 0) {
this.list[index].offsetX = Math.max(offsetX, -80) // 限制最大滑动距离
}
},
handleTouchEnd(index) {
if (this.list[index].offsetX < -40) { // 滑动超过阈值保持打开
this.list[index].offsetX = -80
} else { // 否则回弹
this.list[index].offsetX = 0
}
},
deleteItem(index) {
this.list.splice(index, 1)
}
}
}
</script>
<style>
.list-container {
overflow: hidden;
}
.list-item {
display: flex;
position: relative;
transition: transform 0.3s ease;
}
.content {
flex: 1;
padding: 15px;
background: #fff;
}
.delete-btn {
width: 80px;
background: red;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
</style>
使用 vue-swipe-actions 库
对于更复杂的滑动交互,可以使用专门的开源库简化实现。
安装库:
npm install vue-swipe-actions
基本用法:

<template>
<swipe-action>
<template #left>
<swipe-action-item @click="onLeftClick(item)">
收藏
</swipe-action-item>
</template>
<div class="content">
{{ item.content }}
</div>
<template #right>
<swipe-action-item @click="onDelete(item)" color="red">
删除
</swipe-action-item>
</template>
</swipe-action>
</template>
<script>
import { SwipeAction, SwipeActionItem } from 'vue-swipe-actions'
import 'vue-swipe-actions/dist/vue-swipe-actions.css'
export default {
components: {
SwipeAction,
SwipeActionItem
},
methods: {
onDelete(item) {
// 删除逻辑
},
onLeftClick(item) {
// 其他操作
}
}
}
</script>
实现要点
- 手势检测需要处理 touch 事件,注意移动端兼容性
- 滑动距离应有限制,避免过度滑动
- 添加过渡动画提升用户体验
- 考虑滑动冲突问题,可能需要阻止页面滚动
- 删除操作应有确认机制,防止误触
两种方式各有优劣:原生实现更轻量但需要处理更多细节;使用库更方便但会增加包体积。根据项目需求选择合适方案。






