vue 实现左滑删除
Vue 实现左滑删除功能
左滑删除是移动端常见的交互方式,可以通过 Vue 结合 CSS 和手势事件实现。以下是两种常见的实现方法:
使用 CSS 过渡和 touch 事件
通过监听 touch 事件计算滑动距离,结合 CSS 过渡效果实现左滑动画。
<template>
<div class="list-item" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">
<div class="content">可滑动内容</div>
<div class="delete-btn" @click="handleDelete">删除</div>
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
moveX: 0,
offsetX: 0
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
},
handleTouchMove(e) {
this.moveX = e.touches[0].clientX
this.offsetX = this.moveX - this.startX
if (this.offsetX < 0 && this.offsetX > -100) {
e.currentTarget.style.transform = `translateX(${this.offsetX}px)`
}
},
handleTouchEnd(e) {
if (this.offsetX < -50) {
e.currentTarget.style.transform = 'translateX(-100px)'
} else {
e.currentTarget.style.transform = 'translateX(0)'
}
},
handleDelete() {
// 删除逻辑
}
}
}
</script>
<style>
.list-item {
position: relative;
width: 100%;
height: 60px;
overflow: hidden;
transition: transform 0.3s ease;
}
.content {
position: absolute;
width: 100%;
height: 100%;
background: #fff;
z-index: 1;
}
.delete-btn {
position: absolute;
right: 0;
width: 100px;
height: 100%;
background: red;
color: white;
display: flex;
align-items: center;
justify-content: center;
z-index: 0;
}
</style>
使用第三方库(如 vue-touch)
vue-touch 库封装了 Hammer.js 的手势识别功能,可以更方便地实现滑动操作。
安装依赖:
npm install vue-touch@next hammerjs
实现代码:
<template>
<v-touch @swipeleft="onSwipeLeft" @swiperight="onSwipeRight">
<div class="item" :style="{transform: `translateX(${offsetX}px)`}">
<div class="content">滑动我</div>
<div class="delete-btn" @click="deleteItem">删除</div>
</div>
</v-touch>
</template>
<script>
import { VueTouch } from 'vue-touch'
export default {
components: {
'v-touch': VueTouch
},
data() {
return {
offsetX: 0
}
},
methods: {
onSwipeLeft() {
this.offsetX = -100
},
onSwipeRight() {
this.offsetX = 0
},
deleteItem() {
// 删除逻辑
}
}
}
</script>
<style>
.item {
display: flex;
position: relative;
width: 100%;
height: 60px;
transition: transform 0.3s;
}
.content {
flex: 1;
background: #fff;
}
.delete-btn {
width: 100px;
background: red;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
</style>
实现注意事项
- 滑动距离阈值需要合理设置,通常 50-100px 触发删除按钮显示
- 添加过渡动画提升用户体验
- 移动端需要考虑 touch 事件兼容性
- 列表项需要设置 overflow: hidden 防止内容溢出
- 删除操作需要添加确认机制防止误触
这两种方法都能实现左滑删除功能,第一种更轻量但需要手动处理 touch 事件,第二种使用现成库更简便但会增加包体积。根据项目需求选择合适方案。







