小程序多盒子拖拽排序
在小程序实现多行拖拽排序功能,需要用到uniapp提供的内部插件,moveable-view。
首先,在页面中引入moveable-view插件,并初始化它。然后,在页面中创建多个盒子,并为每个盒子添加moveable-view组件。最后,通过监听moveable-view组件的拖拽事件,实现多行拖拽排序的功能。
# 效果图
主要代码如下
//拖拽开始
handleDragStart(index) {
this.currentIndex = index,
this.firstX = this.list[index].x + 0.01,
this.firstY = this.list[index].y + 0.01,
this.activeIndex = index;
this.oldIndex = index;
},
//拖拽中
handleMoving(e) {
if (e.detail.source !== 'touch' || !this.isEdit) return;
const {
x,
y
} = e.detail;
const currentX = Math.floor((x + this.getItemWidth / 2) / this.getItemWidth);
const currentY = Math.floor((y + this.getItemHeight / 2) / this.getItemHeight);
this.moveToIndex = Math.min(currentY * this.column + currentX, this.list.length - 1);
if (this.oldIndex !== this.moveToIndex && this.oldIndex !== -1 && this.moveToIndex !== -1) {
this.hasChanged = true
const newList = this.deepCopy(this.cloneList);
// 交换位置
newList.splice(this.moveToIndex, 0, ...newList.splice(this.activeIndex, 1));
this.list.forEach((item, index) => {
const itemIndex = newList.findIndex(val => val.name === item.name);
if (index !== this.currentIndex) {
[item.x, item.y] = this.getPosition(itemIndex);
}
});
this.oldIndex = this.moveToIndex;
if (this.moveToIndex == this.currentIndex) {
this.hasChanged = false
}
} else {}
},
//拖拽结束
handleDragEnd(e) {
if (!this.isEdit) return;
if (this.moveToIndex !== -1 && this.activeIndex !== -1 && this.moveToIndex !== this.activeIndex) {
if (!this.hasChanged || (this.moveToIndex == this.currentIndex)) return
this.cloneList.splice(this.moveToIndex, 0, ...this.cloneList.splice(this.activeIndex, 1));
this.initList(this.cloneList);
const endList = this.list.map(item => this.omit(item, ['x', 'y', 'key']));
this.$emit('input', endList);
this.$emit('end', endList);
this.activeIndex = -1;
this.oldIndex = -1;
this.disabled = true;
this.list.forEach((item, index) => {
if (this.moveToIndex === index) {
let y = Math.floor(index / 4) * 99.99
if (y == 0) {
item.y = 0.01
} else {
item.y = y
}
}
})
this.moveToIndex = -1;
this.hasChanged = false
} else {
this.changeFirst(this.currentIndex, this.firstX, this.firstY)
}
},
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
上次更新: 2024/06/04, 17:57:35