grouped-picker.vue
15.6 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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
<template>
<!-- 分层选项选择器:顶部 tab → 左侧竖排侧栏 → 右侧列表(第 3 层做分组标题)
行的勾选态由本组件的 draft 数据派生,不用 u-checkbox:
u-checkbox 的勾选态是组件内部状态(u-checkbox.vue:199-221 只在 init 时从父组派生),
而 u-checkbox-group 是把每个子实例的内部 isChecked 回读成数组(u-checkbox-group.vue:95-112),
子实例卸载后仍留在 children 里 —— 本弹层「切 tab 就换一批行」正好会命中这个坑(会读出幽灵勾选/重复值)。 -->
<up-popup :show="show" mode="bottom" :round="16" :safe-area-inset-bottom="true" :closeable="true"
close-icon-color="#999999" @close="handleClose">
<view class="gp-wrap">
<!-- 标题 + 多选已选数(已选项可能落在别的 tab,行不可见,必须靠这里和侧栏角标提示) -->
<view class="gp-header">
<text class="gp-title">{{ title || '请选择' }}</text>
<text v-if="multiple && hintText" class="gp-hint">{{ hintText }}</text>
</view>
<!-- 搜索:命中时跳过分组、对全量过滤,避免「切在某个 tab 里搜不到其它 tab 的项」 -->
<view class="gp-search">
<up-input v-model="keyword" :placeholder="`搜索${title || ''}`" clearable border="surround"
shape="circle"></up-input>
</view>
<!-- 第 1 层:顶部 tab -->
<up-tabs v-if="!isSearching && tabList.length > 1" :list="tabList" :scrollable="true"
v-model:current="tabIdx" @change="onTabChange" :lineWidth="30"></up-tabs>
<view class="gp-body">
<!-- 第 2 层:左侧竖排侧栏 -->
<scroll-view v-if="!isSearching && sides.length > 0" scroll-y class="gp-side">
<view v-for="(side, idx) in sides" :key="side.key" class="gp-side-item"
:class="{ 'is-active': idx === sideIdx }" @click="switchSide(idx)">
<text class="gp-side-text">{{ side.label }}</text>
<text v-if="side.count > 0" class="gp-side-badge">{{ side.count }}</text>
</view>
</scroll-view>
<!-- 第 3 层及更深:右侧列表,按最深可用层做分组标题 -->
<scroll-view scroll-y class="gp-list" :key="listKey">
<view v-for="group in visibleGroups" :key="group.key" class="gp-group">
<view class="gp-group-title">{{ group.label }}</view>
<view v-for="row in group.rows" :key="row.value" class="gp-row"
:class="{ 'is-selected': isSelected(row), 'is-locked': isLocked(row) }" @click="onRowClick(row)">
<view class="gp-check" :class="{ 'is-checked': isSelected(row) }">
<text v-if="isSelected(row)" class="gp-check-mark">✓</text>
</view>
<view class="gp-row-main">
<text class="gp-row-label">{{ row.label }}</text>
<!-- 搜索态下补层级面包屑,否则不知道命中的项属于哪个分组 -->
<text v-if="breadcrumb(row)" class="gp-row-crumb">{{ breadcrumb(row) }}</text>
</view>
<view v-if="needQuantity && isSelected(row)" class="gp-row-qty" @click.stop>
<u-number-box v-model="draftQty[row.value]" :min="0" :step="1"></u-number-box>
<text v-if="unit" class="gp-row-unit">{{ unit }}</text>
</view>
</view>
</view>
<view v-if="visibleGroups.length === 0" class="gp-empty">暂无数据</view>
</scroll-view>
</view>
<view class="gp-actions">
<view class="gp-action-item">
<up-button type="default" text="取消" @click="handleClose"></up-button>
</view>
<!-- 单选点行即提交,无需确定;多选才给确定按钮 -->
<view v-if="multiple" class="gp-action-item">
<up-button type="primary" :text="confirmText" @click="handleConfirm"></up-button>
</view>
</view>
</view>
</up-popup>
</template>
<script setup>
import { ref, reactive, computed, watch, defineProps, defineEmits } from 'vue'
// ========== Props ==========
const props = defineProps({
show: { type: Boolean, default: false },
title: { type: String, default: '' },
// 全量选项(后端扁平行):[{ label, value, path: [{ key, label }] }]
options: { type: Array, default: () => [] },
multiple: { type: Boolean, default: false },
// Infinity 表示不限(页面用 maxCountOf(item, Infinity) 传入)
maxCount: { type: Number, default: Infinity },
needQuantity: { type: Boolean, default: false },
// 单选传字符串、多选传数组
value: { type: [String, Array], default: '' },
// { 选项值: 数量 }
quantities: { type: Object, default: () => ({}) },
unit: { type: String, default: '' }
})
const emit = defineEmits(['update:show', 'confirm'])
// ========== 内部状态 ==========
// draft:弹层内的编辑副本。取消直接丢弃,确定才一次性回传,避免半选态污染页面表单
const keyword = ref('')
const tabIdx = ref(0)
const sideIdx = ref(0)
const draftSelected = ref([])
const draftValue = ref('')
// 数量表用 reactive 而非 ref:模板里要 v-model 到动态键(draftQty[row.value]),
// reactive 直接写属性即可,不依赖编译器把 ref 改写成 .value[key](本仓无法本地构建,不赌这个)
const draftQty = reactive({})
// ========== 组树 ==========
const rows = computed(() =>
(props.options || []).filter(o => o && o.value !== undefined && o.value !== null)
)
// 层数按「行里 path 的最大长度」定,兼容同一个字段里长短不一的行
const depth = computed(() => rows.value.reduce((m, r) => Math.max(m, (r.path || []).length), 0))
// 层级→用途映射:>=3 层才有侧栏;2 层只用 tab;1 层直接平铺(带该层名分组)
const tabLevel = computed(() => (depth.value >= 2 ? 0 : -1))
const sideLevel = computed(() => (depth.value >= 3 ? 1 : -1))
const groupStart = computed(() => {
if (depth.value >= 3) return 2
if (depth.value === 2) return 1
return 0
})
const nodeAt = (row, i) => {
const p = row.path
return p && p[i] ? p[i] : null
}
const keyAt = (row, i) => {
const n = nodeAt(row, i)
return n ? String(n.key || n.label || '') : ''
}
const labelAt = (row, i) => {
const n = nodeAt(row, i)
return n ? String(n.label || n.key || '') : ''
}
// 分组键用 \u0001 连接(层级值里不会出现该字符),分组名用 ' / ' 连接更深层
const groupKeyOf = (row) => {
const parts = []
for (let i = groupStart.value; i < (row.path || []).length; i++) parts.push(keyAt(row, i))
return parts.join('\u0001') || '__none__'
}
const groupLabelOf = (row) => {
const parts = []
for (let i = groupStart.value; i < (row.path || []).length; i++) parts.push(labelAt(row, i))
return parts.join(' / ') || '其他'
}
const tabs = computed(() => {
if (tabLevel.value < 0) return []
const seen = new Map()
for (const r of rows.value) {
const k = keyAt(r, tabLevel.value)
if (!seen.has(k)) seen.set(k, { key: k, label: labelAt(r, tabLevel.value) })
}
return Array.from(seen.values())
})
const tabList = computed(() => tabs.value.map(t => ({ name: t.label })))
const activeTab = computed(() => tabs.value[tabIdx.value] || null)
const rowsInTab = computed(() => {
if (tabLevel.value < 0) return rows.value
const t = activeTab.value
if (!t) return []
return rows.value.filter(r => keyAt(r, tabLevel.value) === t.key)
})
const sides = computed(() => {
if (sideLevel.value < 0) return []
const seen = new Map()
for (const r of rowsInTab.value) {
const k = keyAt(r, sideLevel.value)
if (!seen.has(k)) seen.set(k, { key: k, label: labelAt(r, sideLevel.value), count: 0 })
}
const list = Array.from(seen.values())
// 已选数量角标:已选项的勾选框在别的 tab/侧栏时是卸载状态,只能靠角标让用户知道选过什么
for (const side of list) {
side.count = draftSelected.value.filter(v => {
const row = rows.value.find(r => String(r.value) === v)
return row ? keyAt(row, sideLevel.value) === side.key : false
}).length
}
return list
})
const activeSide = computed(() => sides.value[sideIdx.value] || null)
const rowsInSide = computed(() => {
if (sideLevel.value < 0) return rowsInTab.value
const s = activeSide.value
if (!s) return []
return rowsInTab.value.filter(r => keyAt(r, sideLevel.value) === s.key)
})
const isSearching = computed(() => keyword.value.trim() !== '')
const searchedRows = computed(() => {
const kw = keyword.value.trim().toLowerCase()
if (!kw) return []
return rows.value.filter(r => String(r.label || '').toLowerCase().indexOf(kw) > -1)
})
const visibleGroups = computed(() => {
if (isSearching.value) {
return searchedRows.value.length
? [{ key: '__search__', label: `搜索结果(${searchedRows.value.length})`, rows: searchedRows.value }]
: []
}
const out = []
const seen = new Map()
for (const r of rowsInSide.value) {
const k = groupKeyOf(r)
if (!seen.has(k)) {
const g = { key: k, label: groupLabelOf(r), rows: [] }
seen.set(k, g)
out.push(g)
}
seen.get(k).rows.push(r)
}
return out
})
// 切 tab/侧栏时换 key 让 scroll-view 重建,把滚动位置带回顶部
const listKey = computed(() => `${tabIdx.value}|${sideIdx.value}`)
const breadcrumb = (row) =>
isSearching.value ? (row.path || []).map(n => n.label || n.key).join(' / ') : ''
// ========== 选中态 ==========
const isSelected = (row) => {
const v = String(row.value)
return props.multiple ? draftSelected.value.indexOf(v) > -1 : draftValue.value === v
}
// 到上限后禁用未选中项(同页面 isOptionLocked 的口径:不回写截断,只挡新增)
const isLocked = (row) => {
if (!props.multiple) return false
const max = props.maxCount
if (max === Infinity || max === undefined || max === null) return false
return draftSelected.value.length >= max && !isSelected(row)
}
const hintText = computed(() => {
const max = props.maxCount
const n = draftSelected.value.length
if (max === Infinity || max === undefined || max === null) return n ? `已选 ${n}` : ''
return `已选 ${n}/${max}`
})
const confirmText = computed(() =>
draftSelected.value.length ? `确定(${draftSelected.value.length})` : '确定'
)
// ========== 交互 ==========
const onTabChange = () => {
// v-model:current 已写好 tabIdx,这里只把侧栏带回第一项
sideIdx.value = 0
}
const switchSide = (idx) => {
sideIdx.value = idx
}
const onRowClick = (row) => {
const v = String(row.value)
if (props.multiple) {
if (isLocked(row)) {
uni.showToast({ title: `最多选择 ${props.maxCount} 项`, icon: 'none' })
return
}
const i = draftSelected.value.indexOf(v)
if (i > -1) {
draftSelected.value.splice(i, 1)
} else {
draftSelected.value.push(v)
}
return
}
// 单选:点行即确认并关闭,与底部 actionSheet 的即时选中语义一致
draftValue.value = v
handleConfirm()
}
const handleConfirm = () => {
const sel = props.multiple
? rows.value.filter(r => draftSelected.value.indexOf(String(r.value)) > -1)
: rows.value.filter(r => String(r.value) === draftValue.value)
const labels = sel.map(r => r.label)
let labelText = ''
if (props.multiple) {
const joined = labels.join('、')
labelText = joined.length > 30 ? `已选 ${labels.length} 项` : joined
} else {
labelText = labels[0] || ''
}
const quantities = {}
if (props.needQuantity) {
sel.forEach(r => {
const raw = draftQty[String(r.value)]
if (raw !== '' && raw !== null && raw !== undefined) {
quantities[String(r.value)] = raw
}
})
}
emit('confirm', {
values: props.multiple ? draftSelected.value.slice() : draftValue.value,
labelText,
quantities
})
emit('update:show', false)
}
const handleClose = () => {
emit('update:show', false)
}
// 每次打开用页面当前值重置 draft,并定位到第一个已选项所在的分区
const resetPosition = () => {
tabIdx.value = 0
sideIdx.value = 0
const sel = props.multiple ? draftSelected.value : draftValue.value ? [draftValue.value] : []
if (!sel.length) return
const first = rows.value.find(r => sel.indexOf(String(r.value)) > -1)
if (!first) return
if (tabLevel.value >= 0) {
const i = tabs.value.findIndex(t => t.key === keyAt(first, tabLevel.value))
if (i > -1) tabIdx.value = i
}
if (sideLevel.value >= 0) {
const i = sides.value.findIndex(s => s.key === keyAt(first, sideLevel.value))
if (i > -1) sideIdx.value = i
}
}
watch(
() => props.show,
(val) => {
if (!val) return
keyword.value = ''
draftSelected.value = props.multiple && Array.isArray(props.value) ? props.value.map(v => String(v)) : []
draftValue.value = !props.multiple && props.value !== null && props.value !== undefined ? String(props.value) : ''
// 先清空再灌入:reactive 对象上直接 Object.assign 会把上次打开残留的键留下
Object.keys(draftQty).forEach(k => delete draftQty[k])
Object.assign(draftQty, props.quantities || {})
resetPosition()
}
)
</script>
<style scoped lang="scss">
.gp-wrap {
display: flex;
flex-direction: column;
}
.gp-header {
display: flex;
align-items: baseline;
justify-content: space-between;
padding: 30rpx 30rpx 0;
}
.gp-title {
font-size: 32rpx;
font-weight: 600;
color: #303133;
}
.gp-hint {
font-size: 24rpx;
color: #909399;
}
.gp-search {
padding: 20rpx 30rpx 10rpx;
}
.gp-body {
display: flex;
height: 700rpx;
border-top: 1rpx solid #f2f3f5;
}
/* 侧栏 */
.gp-side {
width: 200rpx;
height: 100%;
background: #f7f8fa;
}
.gp-side-item {
position: relative;
display: flex;
align-items: center;
justify-content: center;
min-height: 88rpx;
padding: 0 12rpx;
font-size: 26rpx;
color: #606266;
text-align: center;
&.is-active {
background: #ffffff;
color: #2979ff;
font-weight: 600;
border-left: 6rpx solid #2979ff;
}
}
.gp-side-text {
font-size: 26rpx;
}
.gp-side-badge {
position: absolute;
top: 8rpx;
right: 8rpx;
min-width: 28rpx;
height: 28rpx;
padding: 0 6rpx;
border-radius: 14rpx;
background: #2979ff;
color: #ffffff;
font-size: 20rpx;
line-height: 28rpx;
text-align: center;
}
/* 右侧列表 */
.gp-list {
flex: 1;
height: 100%;
}
.gp-group-title {
/* 吸顶:小程序 webview 下生效;skyline 不支持时会静默退化为普通标题,不影响可用性 */
position: sticky;
top: 0;
z-index: 2;
padding: 14rpx 24rpx;
background: #f2f3f5;
font-size: 24rpx;
color: #909399;
}
.gp-row {
display: flex;
align-items: center;
padding: 22rpx 24rpx;
border-bottom: 1rpx solid #f2f3f5;
&.is-locked {
opacity: 0.4;
}
}
.gp-check {
flex-shrink: 0;
width: 36rpx;
height: 36rpx;
margin-right: 18rpx;
border: 2rpx solid #c8c9cc;
border-radius: 6rpx;
display: flex;
align-items: center;
justify-content: center;
&.is-checked {
background: #2979ff;
border-color: #2979ff;
}
}
.gp-check-mark {
color: #ffffff;
font-size: 24rpx;
line-height: 1;
}
.gp-row-main {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
}
.gp-row-label {
font-size: 28rpx;
color: #303133;
}
.gp-row-crumb {
margin-top: 4rpx;
font-size: 22rpx;
color: #909399;
}
.gp-row-qty {
flex-shrink: 0;
display: flex;
align-items: center;
margin-left: 12rpx;
}
.gp-row-unit {
margin-left: 8rpx;
font-size: 24rpx;
color: #909399;
}
.gp-empty {
padding: 60rpx 0;
font-size: 26rpx;
color: #c0c4cc;
text-align: center;
}
.gp-actions {
display: flex;
align-items: center;
border-top: 1rpx solid #f2f3f5;
}
.gp-action-item {
flex: 1;
padding: 20rpx;
}
</style>