vue实现左滑删除
实现左滑删除的基本思路
在Vue中实现左滑删除功能,通常需要结合触摸事件(touchstart、touchmove、touchend)和CSS过渡效果。通过监听用户的手势滑动,动态调整元素的水平位置,当滑动距离达到阈值时触发删除操作。
监听触摸事件
为需要实现左滑删除的元素绑定触摸事件。通过计算触摸起始点和移动点的差值,确定滑动的方向和距离。
data() {
return {
startX: 0,
moveX: 0,
translateX: 0
};
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX;
},
handleTouchMove(e) {
this.moveX = e.touches[0].clientX;
this.translateX = this.moveX - this.startX;
// 限制向右滑动
if (this.translateX > 0) {
this.translateX = 0;
}
},
handleTouchEnd() {
// 滑动距离超过阈值时触发删除
if (this.translateX < -60) {
this.deleteItem();
} else {
this.translateX = 0;
}
},
deleteItem() {
// 删除逻辑
}
}
动态绑定样式
根据计算出的滑动距离,动态绑定元素的transform样式,实现滑动效果。
<template>
<div
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
:style="{ transform: `translateX(${translateX}px)` }"
>
<!-- 内容 -->
</div>
</template>
添加过渡效果
为了使滑动更加平滑,可以添加CSS过渡效果。
div {
transition: transform 0.3s ease;
}
完整组件示例
以下是一个完整的Vue组件示例,实现了左滑删除功能。
<template>
<div class="list-container">
<div
v-for="(item, index) in list"
:key="index"
class="list-item"
@touchstart="handleTouchStart(index, $event)"
@touchmove="handleTouchMove(index, $event)"
@touchend="handleTouchEnd(index)"
:style="{ transform: `translateX(${item.translateX}px)` }"
>
<div class="item-content">
{{ item.text }}
</div>
<div class="delete-button" @click="deleteItem(index)">
删除
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{ text: 'Item 1', translateX: 0 },
{ text: 'Item 2', translateX: 0 },
{ text: 'Item 3', translateX: 0 }
],
startX: 0
};
},
methods: {
handleTouchStart(index, e) {
this.startX = e.touches[0].clientX;
},
handleTouchMove(index, e) {
const moveX = e.touches[0].clientX;
this.list[index].translateX = moveX - this.startX;
if (this.list[index].translateX > 0) {
this.list[index].translateX = 0;
}
},
handleTouchEnd(index) {
if (this.list[index].translateX < -60) {
this.list[index].translateX = -80;
} else {
this.list[index].translateX = 0;
}
},
deleteItem(index) {
this.list.splice(index, 1);
}
}
};
</script>
<style>
.list-container {
width: 100%;
}
.list-item {
display: flex;
align-items: center;
width: 100%;
height: 60px;
border-bottom: 1px solid #eee;
position: relative;
overflow: hidden;
transition: transform 0.3s ease;
}
.item-content {
width: 100%;
padding: 0 15px;
}
.delete-button {
position: absolute;
right: 0;
width: 80px;
height: 100%;
background: #ff4444;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
</style>
注意事项
- 在移动端开发中,需要考虑触摸事件的兼容性。
- 滑动阈值可以根据实际需求调整。
- 删除按钮的宽度应与滑动阈值匹配,确保用户滑动到足够距离时按钮完全显示。
- 为了防止页面滚动与滑动删除冲突,可以在
touchmove事件中调用e.preventDefault()。







