1. uni-app实现列表拖动排序
拖动排序的代码
以下是实现列表拖动排序的代码,要求兼容小程序和APP的示例:
<template>
<view class="container">
<view
class="item"
v-for="(item, index) in list"
:key="item.id"
:ref="'item-' + index"
:data-index="index"
:style="{ transform: 'translateY(' + item.translateY + 'px)' }"
@touchstart="onTouchStart(index, $event)"
@touchmove="onTouchMove($event)"
@touchend="onTouchEnd"
>
{{ item.name }}
</view>
</view>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, name: 'item 1', translateY: 0, startY: 0 },
{ id: 2, name: 'item 2', translateY: 0, startY: 0 },
{ id: 3, name: 'item 3', translateY: 0, startY: 0 },
{ id: 4, name: 'item 4', translateY: 0, startY: 0 },
],
curIndex: -1,
};
},
methods: {
onTouchStart(index, event) {
this.list.forEach((item) => {
item.translateY = 0;
});
this.curIndex = index;
this.list[index].startY = event.touches[0].clientY;
},
onTouchMove(event) {
const {
clientY
} = event.touches[0];
const translateY = clientY - this.list[this.curIndex].startY;
this.list[this.curIndex].translateY = translateY;
if (translateY > 0) {
for (let i = this.curIndex + 1, len = this.list.length; i < len; i++) {
const distance = i - this.curIndex;
if (this.list[i].translateY !== distance * 60) {
this.list[i].translateY = distance * 60;
}
}
} else if (translateY < 0) {
for (let i = this.curIndex - 1; i >= 0; i--) {
const distance = this.curIndex - i;
if (this.list[i].translateY !== distance * -60) {
this.list[i].translateY = distance * -60;
}
}
}
},
onTouchEnd() {
const curItem = this.list[this.curIndex];
const curY = curItem.translateY;
const distance = Math.round(curY / 60);
const targetIndex = this.curIndex + distance;
if (targetIndex >= 0 && targetIndex < this.list.length && targetIndex !== this.curIndex) {
const moveItem = this.list.splice(this.curIndex, 1)[0];
this.list.splice(targetIndex, 0, moveItem);
this.$forceUpdate();
} else {
this.list[this.curIndex].translateY = 0;
}
this.curIndex = -1;
},
},
};
</script>
<style>
.container {
display: flex;
flex-direction: column;
align-items: center;
}
.item {
width: 100%;
height: 60px;
line-height: 60px;
border-bottom: 1px solid #eee;
text-align: center;
background-color: #fff;
font-size: 16px;
user-select: none;
}
</style>
此示例中,使用touch事件处理列表项的拖动排序,通过计算移动距离,实现了列表项的位置重排。同时借助translateY属性,使得列表项在拖动过程中能够有平滑的移动效果。
在小程序中使用该组件时,需要在page.json中添加如下配置:
{
"usingComponents": {
"drag-sort-list": "/components/drag-sort-list/drag-sort-list"
}
}
在app中使用该组件时,直接在页面中引入即可。
源码获取方法:
需要完整源码的朋友,希望你能点赞+收藏+评论,然后私信我即可~
会员学习群:
可添加学习会员小助手咨询(微信:mifankeji77)