vue实现左滑动删除
Vue 实现左滑删除功能
监听触摸事件
在 Vue 组件中监听 touchstart、touchmove 和 touchend 事件,记录触摸起始位置和移动距离。
data() {
return {
startX: 0,
moveX: 0,
isDragging: false
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
this.isDragging = false
},
handleTouchMove(e) {
this.moveX = e.touches[0].clientX - this.startX
this.isDragging = Math.abs(this.moveX) > 10
},
handleTouchEnd() {
if (this.isDragging) {
// 处理滑动结束逻辑
}
}
}
绑定事件到元素
在模板中为需要滑动的元素绑定事件处理器。
<div
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
:style="{ transform: `translateX(${moveX}px)` }"
>
<!-- 内容 -->
</div>
实现滑动动画
使用 CSS 过渡效果让滑动更流畅,通过 Vue 的响应式数据控制 transform 属性。

.slide-item {
transition: transform 0.3s ease;
}
添加删除按钮
在滑动元素后面放置删除按钮,通过滑动距离控制按钮显示。
<div class="slide-container">
<div class="slide-content"
:style="{ transform: `translateX(${moveX}px)` }">
<!-- 主要内容 -->
</div>
<div class="slide-action" v-show="isDragging && moveX < 0">
<button @click="handleDelete">删除</button>
</div>
</div>
处理删除逻辑
在滑动结束时判断滑动距离,如果超过阈值则触发删除操作。

handleTouchEnd() {
if (this.isDragging) {
if (this.moveX < -100) {
this.$emit('delete')
} else {
this.moveX = 0
}
this.isDragging = false
}
}
优化体验
添加阈值判断和自动回弹效果,提升用户体验。
handleTouchMove(e) {
const currentX = e.touches[0].clientX
this.moveX = Math.min(0, Math.max(-100, currentX - this.startX))
this.isDragging = Math.abs(this.moveX) > 10
}
完整组件示例
<template>
<div class="slide-container">
<div
class="slide-content"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
:style="{ transform: `translateX(${moveX}px)` }"
>
<slot></slot>
</div>
<div class="slide-action" v-show="isDragging && moveX < 0">
<button @click="$emit('delete')">删除</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
moveX: 0,
isDragging: false
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
this.isDragging = false
},
handleTouchMove(e) {
const currentX = e.touches[0].clientX
this.moveX = Math.min(0, Math.max(-100, currentX - this.startX))
this.isDragging = Math.abs(this.moveX) > 10
},
handleTouchEnd() {
if (this.isDragging) {
if (this.moveX < -50) {
this.moveX = -80
} else {
this.moveX = 0
}
this.isDragging = false
}
}
}
}
</script>
<style>
.slide-container {
position: relative;
overflow: hidden;
}
.slide-content {
transition: transform 0.3s ease;
z-index: 1;
background: white;
}
.slide-action {
position: absolute;
right: 0;
top: 0;
bottom: 0;
width: 80px;
display: flex;
align-items: center;
justify-content: center;
background: #ff4444;
}
</style>
使用第三方库
对于更复杂的需求,可以考虑使用现成的 Vue 滑动组件库,如 vue-touch-ripple 或 v-touch。
npm install vue-touch-ripple
import VueTouchRipple from 'vue-touch-ripple'
Vue.use(VueTouchRipple)






