uni-app使用movable-area 实现数据的拖拽排序功能
template部分
<movable-area :style="getAreaStyle">
<movable-view class="table-row"
v-for="v,i in move.list"
:key="v.id"
:y="v.y"
@change="handle_moving"
direction="vertical"
@touchstart="handle_dragstart(i,v)"
@touchend="handle_dragend(i,v)"
@longpress="handleLongpress(v)"
:disabled="move.disabled">
<view class="table-cell">{{i+1}}</view>
<view class="table-cell">选择物料</view>
</movable-view>
</movable-area>
.table-cell,.table-row{
height:50rpx;
}
.table-row{
width:100%;
display: flex;
}
.table-cell{
width:200rpx;
}
注意使用movable-area时需要设置高度和宽度 否则默认10
js部分
const move = reactive({
list:[],
disabled: true,
activeIndex: -1,
moveToIndex: -1,
oldIndex: -1,
tempDragInfo: {
y: ''
},
cloneList: [],
longpress: true,
})
// 获取位置
const getPosition_y = (index) => {
return index * 25
}
const getAreaStyle = computed(() => {
return {
width: '100%',
height: move.list.length * 25 + 'px'
}
})
// 初始化列表
const initList = (list = []) => {
const newList = JSON.parse(JSON.stringify(list));
move.list = newList.map((item, index) => {
return {
...item,
y: getPosition_y(index)
}
})
move.cloneList = JSON.parse(JSON.stringify(move.list));
}
// 开始拖拽
const handle_dragstart = (i,v) => {
if(!v.id){
return false;
}
move.activeIndex = i;
move.oldIndex = i;
}
// 拖拽结束
const handle_dragend = (i,v) => {
if(!v.id){
return false;
}
if (move.disabled) return;
if (move.moveToIndex != -1 && move.activeIndex != -1 && move.activeIndex != move.moveToIndex) {
move.cloneList.splice(move.moveToIndex, 0, ...move.cloneList.splice(move.activeIndex, 1));
} else {
move.list[move.activeIndex]['y'] = move.tempDragInfo.y;
}
initList(move.cloneList)
move.activeIndex = -1;
move.oldIndex = -1;
move.moveToIndex = -1;
move.disabled = true;
}
// 移动
const handle_moving = (e) => {
console.log({e})
if (e.detail.source !== 'touch') return;
let y = e.detail.y;
move.tempDragInfo.y = y;
const currentY = Math.floor((y + 12.5) / 25)
move.moveToIndex = Math.min(currentY, move.list.length - 1);
if (move.oldIndex != move.moveToIndex && move.oldIndex != -1 && move.moveToIndex != -1) {
const newList = JSON.parse(JSON.stringify(move.cloneList));
let splicItem = newList.splice(move.activeIndex, 1)[0]
newList.splice(move.moveToIndex, 0, splicItem);
move.list.forEach((item, index) => {
if (index != move.activeIndex) {
const itemIndex = newList.findIndex(val => val?.id === item?.id);
item['y'] = getPosition_y(itemIndex);
}
});
move.oldIndex = move.moveToIndex;
}
}
const handleLongpress = (v) => {
if(!v.id){
return false
}
move.disabled = false;
}
原文地址:https://blog.csdn.net/cyj0919/article/details/143366644
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!