u-dragsort.vue
11.9 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
<template>
<view class="u-dragsort"
:class="[direction == 'horizontal' ? 'u-dragsort--horizontal' : '', direction == 'all' ? 'u-dragsort--all' : '']">
<movable-area class="u-dragsort-area" :style="movableAreaStyle">
<movable-view v-for="(item, index) in list" :key="item.id" :id="`u-dragsort-item-${index}`"
class="u-dragsort-item" :class="{ 'dragging': dragIndex === index }"
:direction="direction === 'all' ? 'all' : direction" :x="item.x" :y="item.y" :inertia="false"
:disabled="!draggable || (item.draggable === false)" @change="onChange(index, $event)"
@touchstart="onTouchStart(index)" @touchend="onTouchEnd" @touchcancel="onTouchEnd">
<view class="u-dragsort-item-content">
<slot :item="item" :index="index">
{{ item.label }}
</slot>
</view>
</movable-view>
</movable-area>
</view>
</template>
<script>
import { mpMixin } from '../../libs/mixin/mpMixin';
import { mixin } from '../../libs/mixin/mixin';
import { addStyle, addUnit, sleep } from '../../libs/function/index';
export default {
name: 'u-dragsort',
// #ifdef MP
mixins: [mpMixin, mixin,],
// #endif
// #ifndef MP
mixins: [mixin],
// #endif
props: {
initialList: {
type: Array,
required: true,
default: () => []
},
draggable: {
type: Boolean,
default: true
},
direction: {
type: String,
default: 'vertical',
validator: value => ['vertical', 'horizontal', 'all'].includes(value)
},
// 新增列数属性,用于all模式
columns: {
type: Number,
default: 3
}
},
data() {
return {
list: [],
dragIndex: -1,
itemHeight: 40,
itemWidth: 80,
areaWidth: 0, // 可拖动区域宽度
areaHeight: 0, // 可拖动区域高度
originalPositions: [], // 保存原始位置
currentPosition: {
x: 0,
y: 0
}
};
},
computed: {
movableAreaStyle() {
if (this.direction === 'vertical') {
return {
height: `${this.list.length * this.itemHeight}px`,
width: '100%'
};
} else if (this.direction === 'horizontal') {
return {
height: '100%',
width: `${this.list.length * this.itemWidth}px`
};
} else {
// all模式,计算网格布局所需的高度
const rows = Math.ceil(this.list.length / this.columns);
return {
height: `${rows * this.itemHeight}px`,
width: '100%'
};
}
}
},
emits: ['drag-end'],
async mounted() {
await this.$nextTick();
this.initList();
this.calculateItemSize();
this.calculateAreaSize();
},
methods: {
initList() {
// 初始化列表项的位置
this.list = this.initialList.map((item, index) => {
let x = 0, y = 0;
if (this.direction === 'horizontal') {
x = index * this.itemWidth;
y = 0;
} else if (this.direction === 'vertical') {
x = 0;
y = index * this.itemHeight;
} else {
// all模式,网格布局
const col = index % this.columns;
const row = Math.floor(index / this.columns);
x = col * this.itemWidth;
y = row * this.itemHeight;
}
return {
...item,
x,
y
};
});
// 保存初始位置
this.saveOriginalPositions();
},
saveOriginalPositions() {
// 保存当前位置作为原始位置
this.originalPositions = this.list.map(item => ({
x: item.x,
y: item.y
}));
},
async calculateItemSize() {
// 计算项目尺寸
await sleep(30);
return new Promise((resolve) => {
uni.createSelectorQuery()
.in(this)
.select('.u-dragsort-item-content')
.boundingClientRect(res => {
if (res) {
this.itemHeight = res.height || 40;
this.itemWidth = res.width || 80;
// 更新所有项目的位置
this.updatePositions();
// 保存原始位置
this.saveOriginalPositions();
}
resolve(res);
})
.exec();
});
},
async calculateAreaSize() {
// 计算可拖动区域尺寸
await sleep(30);
return new Promise((resolve) => {
uni.createSelectorQuery()
.in(this)
.select('.u-dragsort-area')
.boundingClientRect(res => {
if (res) {
this.areaWidth = res.width || 300;
this.areaHeight = res.height || 300;
}
resolve(res);
})
.exec();
});
},
updatePositions() {
// 更新所有项目的位置
this.list.forEach((item, index) => {
if (this.direction === 'vertical') {
item.y = index * this.itemHeight;
item.x = 0;
} else if (this.direction === 'horizontal') {
item.x = index * this.itemWidth;
item.y = 0;
} else {
// all模式,网格布局
const col = index % this.columns;
const row = Math.floor(index / this.columns);
item.x = col * this.itemWidth;
item.y = row * this.itemHeight;
}
});
},
onTouchStart(index) {
this.dragIndex = index;
// 保存当前位置作为原始位置
this.saveOriginalPositions();
},
onChange(index, event) {
if (!event.detail.source || event.detail.source !== 'touch') return;
this.currentPosition.x = event.detail.x;
this.currentPosition.y = event.detail.y;
// all模式下使用更智能的位置计算
if (this.direction === 'all') {
this.handleAllModeChange(index);
} else {
// 原有的垂直和水平模式逻辑
let itemSize = 0;
let targetIndex = -1;
if (this.direction === 'vertical') {
itemSize = this.itemHeight;
targetIndex = Math.max(0, Math.min(
Math.round(this.currentPosition.y / itemSize),
this.list.length - 1
));
} else if (this.direction === 'horizontal') {
itemSize = this.itemWidth;
targetIndex = Math.max(0, Math.min(
Math.round(this.currentPosition.x / itemSize),
this.list.length - 1
));
}
// 如果位置发生变化,则重新排序
if (targetIndex !== index) {
this.reorderItems(index, targetIndex);
}
}
},
handleAllModeChange(index) {
// 在all模式下,根据当前位置计算最近的网格位置
const col = Math.max(0, Math.min(Math.round(this.currentPosition.x / this.itemWidth), this.columns - 1));
const row = Math.max(0, Math.round(this.currentPosition.y / this.itemHeight));
// 计算目标索引
let targetIndex = row * this.columns + col;
targetIndex = Math.max(0, Math.min(targetIndex, this.list.length - 1));
// 如果位置发生变化,则重新排序
if (targetIndex !== index) {
this.reorderItems(index, targetIndex);
}
},
reorderItems(fromIndex, toIndex) {
const movedItem = this.list.splice(fromIndex, 1)[0];
this.list.splice(toIndex, 0, movedItem);
// 震动反馈
if (uni.vibrateShort) {
uni.vibrateShort();
}
// 更新当前拖拽项目的新索引
this.dragIndex = toIndex;
// 更新所有项目的位置
this.updatePositions();
// 保存当前位置作为原始位置
this.saveOriginalPositions();
},
onTouchEnd() {
// 0.001是为了解决拖动过快等某些极限场景下位置还原不生效问题
if (this.direction === 'horizontal') {
this.list[this.dragIndex].x = this.currentPosition.x + 0.001;
} else if (this.direction === 'vertical' || this.direction === 'all') {
this.list[this.dragIndex].y = this.currentPosition.y + 0.001;
this.list[this.dragIndex].x = this.currentPosition.x + 0.001;
}
// 重置到位置,需要延迟触发动,否则无效。
sleep(50).then(() => {
this.list.forEach((item, index) => {
item.x = this.originalPositions[index].x;
item.y = this.originalPositions[index].y;
});
this.dragIndex = -1;
this.$emit('drag-end', [...this.list]);
});
}
},
watch: {
initialList: {
handler() {
this.$nextTick(() => {
this.initList();
});
},
deep: true
},
direction: {
handler() {
this.$nextTick(() => {
this.initList();
this.calculateItemSize();
this.calculateAreaSize();
});
}
},
columns: {
handler() {
if (this.direction === 'all') {
this.$nextTick(() => {
this.initList();
this.updatePositions();
this.saveOriginalPositions();
});
}
}
}
}
};
</script>
<style scoped lang="scss">
.u-dragsort {
width: 100%;
.u-dragsort-area {
width: 100%;
position: relative;
}
.u-dragsort-item {
position: absolute;
width: 100%;
&.dragging {
z-index: 1000;
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}
.u-dragsort-item-content {
padding: 0px;
text-align: center;
box-sizing: border-box;
padding-bottom: 6px;
border-radius: 8rpx;
transition: all 0.3s ease;
}
}
&.u-dragsort--horizontal {
.u-dragsort-area {
display: flex;
white-space: nowrap;
height: auto;
}
.u-dragsort-item {
display: flex;
width: auto;
height: 100%;
}
}
&.u-dragsort--all {
.u-dragsort-area {
height: auto;
}
.u-dragsort-item {
width: auto;
height: auto;
}
}
}
</style>