2 回复
承接双端(Android,iOS)原生插件开发,uni-app开发。欢迎咨询
QQ:1559653449
V X:fan-rising
在uni-app中实现左滑删除功能,虽然现成的插件不多,但我们可以通过自定义组件和手势监听来实现这一功能。以下是一个简单的示例代码,展示如何在uni-app中实现左滑删除效果。
首先,我们创建一个自定义组件SwipeToDelete.vue
,用于包裹需要左滑删除的列表项。
<template>
<view class="container" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd">
<view class="delete-btn" v-if="isDragging && translateX > 50" @click="deleteItem">删除</view>
<view class="item" :style="{ transform: `translateX(${translateX}px)` }">
<slot></slot>
</view>
</view>
</template>
<script>
export default {
data() {
return {
startX: 0,
translateX: 0,
isDragging: false
};
},
methods: {
onTouchStart(e) {
this.startX = e.touches[0].clientX;
this.isDragging = false;
this.translateX = 0;
},
onTouchMove(e) {
let moveX = e.touches[0].clientX - this.startX;
if (moveX < 0) {
this.translateX = moveX;
this.isDragging = true;
}
},
onTouchEnd() {
if (this.translateX > 50) {
this.translateX = 100; // 完全显示删除按钮
} else {
this.translateX = 0;
this.isDragging = false;
}
},
deleteItem() {
this.$emit('delete');
this.translateX = 0;
this.isDragging = false;
}
}
};
</script>
<style scoped>
.container {
position: relative;
display: flex;
align-items: center;
width: 100%;
overflow: hidden;
}
.item {
flex: 1;
background-color: #fff;
padding: 16px;
}
.delete-btn {
position: absolute;
right: 0;
top: 0;
width: 100px;
background-color: red;
color: #fff;
text-align: center;
}
</style>
然后,在父组件中使用这个自定义组件:
<template>
<view>
<swipe-to-delete v-for="(item, index) in items" :key="index" @delete="removeItem(index)">
{{ item.name }}
</swipe-to-delete>
</view>
</template>
<script>
import SwipeToDelete from './components/SwipeToDelete.vue';
export default {
components: {
SwipeToDelete
},
data() {
return {
items: [
{ name: 'Item 1' },
{ name: 'Item 2' },
// 更多项...
]
};
},
methods: {
removeItem(index) {
this.items.splice(index, 1);
}
}
};
</script>
这个示例展示了如何通过监听触摸事件来实现左滑删除效果。你可以根据实际需求进一步优化和美化这个组件。